Reputation: 101
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
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
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
Reputation: 23364
from operator import itemgetter
max(my_dict.iteritems(), key=itemgetter(1))[0]
Upvotes: 2