Search code examples
pythondictionaryfor-loopmax

for loop through dict to find max


There are many examples available that show how to find a max value in a dict. I was curious though why the maximum key / value cannot found in this way.

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])

Visually checking d, it can be seen that d[maxi] is not the max value.


Solution

  • if d[key] > maxi is comparing the current value with the maximum key. The simplest change would be to write if d[key] > d[maxi]. (You could also keep the maximum value as its own variable).