有很多例子可以顯示如何在字典中找到最大值。我很好奇,爲什麼最大的鍵/值不能以這種方式找到。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