有很多例子可以显示如何在字典中找到最大值。我很好奇,为什么最大的键/值不能以这种方式找到。for循环字典找到最大
from random import randint
# Create dict with random keys and values.
d = {randint(1, 99): randint(1, 99) for i, j in enumerate(range(20))}
# Loop through dict to find max value
maxi = 0
for key in d:
if d[key] > maxi:
maxi = key
print(d, d[maxi])
目视确认d,它可以看出,d [MAXI]不是最大值。
如果指定'key'参数,则可以使用'max()'函数。例如:'max(d,lambda x:d [x])' – Matt 2013-02-15 03:24:37
你不应该使用0作为原始的最大值,除非你总是在字典中有正数。 – 2013-02-15 03:25:06
@Matt没有必要在那里丑陋的lambda。使用'max(d,key = d.get)' – wim 2013-02-15 03:47:32