Wednesday, 15 April 2015

python - for loop through dict to find max -



python - for loop through dict to find max -

there many examples available show how find max value in dict. curious though why maximum key / value cannot found in way.

from random import randint # create dict random keys , values. d = {randint(1, 99): randint(1, 99) i, j in enumerate(range(20))} # loop through dict find max value maxi = 0 key in d: if d[key] > maxi: maxi = key print(d, d[maxi])

visually checking d, can seen d[maxi] not max value.

if d[key] > maxi comparing current value maximum key. simplest alter write if d[key] > d[maxi]. (you maintain maximum value own variable).

python dictionary for-loop max

No comments:

Post a Comment