user2105660
user2105660

Reputation: 101

How to pick a key with the highest value

heres an example code of what I have

my_dict = {'a':2, 'b':5, 'c':3, 'd':8, 'e':3}

How could i make it print the key that has the highest value. For example in the above code it would print:

d

thats all i would want to be printed, just the key that had the highest value. help would be appreciated thanks!

Upvotes: 2

Views: 103

Answers (4)

Rushy Panchal
Rushy Panchal

Reputation: 17532

This is slightly different than the others:

d = {'a':2, 'b':5, 'c':3, 'd':8, 'e':3}
new_d = {d[i]:i for i in d.keys()} # reverses the dict {'a': 2} --> {2: 'a'}
new_d[max(new_d.keys())]

Upvotes: 0

Óscar López
Óscar López

Reputation: 236034

Like this:

my_dict = {'a':2, 'b':5, 'c':3, 'd':8, 'e':3}
max(my_dict, key=my_dict.get)
=> 'd'

Notice that max can find the maximum value of any iterable passed as parameter, and the optional key argument specifies a one-argument selector function for determining what's the attribute in each of the objects to be used for finding the maximum value.

Upvotes: 6

iruvar
iruvar

Reputation: 23364

from operator import itemgetter
max(my_dict.iteritems(), key=itemgetter(1))[0]

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304225

Use a key with max

max(my_dict, key=my_dict.get)

Upvotes: 8

Related Questions