Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the key of the max value in a dictionary the pythonic way [duplicate]

Tags:

python

max

Given a dictionary d where the key values pair consist of a string as key and an integer as value, I want to print the key string where the value is the maximum.

Of course I can loop over d.items(), store the maximum and its key and output the latter after the for loop. But is there a more "pythonic" way just using just a max function construct like

print max(...)
like image 591
halloleo Avatar asked Sep 13 '12 08:09

halloleo


1 Answers

print max(d.keys(), key=lambda x: d[x]) 

or even shorter (from comment):

print max(d, key=d.get)
like image 167
Lev Levitsky Avatar answered Nov 15 '22 20:11

Lev Levitsky