Jack J
Jack J

Reputation: 1644

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.

Upvotes: 0

Views: 16140

Answers (5)

Yadong Du
Yadong Du

Reputation: 1

for key, value in your_dict.items():
   x=max(your_dict,key=your_dict.get)
print("key with the maxi value:",x)

Upvotes: 0

Deepak Kadarivel
Deepak Kadarivel

Reputation: 189

An alternative to this would be to get key, value using dictionary items() function and compare the values to find the max.

max_key = None
max_val = None

for key, val in your_dict.items():

    if max_val is None or val > max_val:
        max_val = val
        max_key = key


print(max_key, max_val)

Upvotes: 0

Rusty Rob
Rusty Rob

Reputation: 17193

>>> d = {"a": 5, "b": 99, "c": 3}
>>> max(d, key=d.get)
'b'

Upvotes: 2

marcelocra
marcelocra

Reputation: 2503

The problem with your code is that the first time you find a value bigger than 0 you store the key instead of the value. Then you compare the next value with the last key you stored.

In the end you store a number that is not what you want (I don't know if there is even a logic for the number that end up in maxi - I guess is just another random number).

Upvotes: 1

hobbs
hobbs

Reputation: 240314

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

Upvotes: 4

Related Questions