Print the key of the max value in a dictionary the

2019-01-23 18:31发布

问题:

This question already has an answer here:

  • Getting key with maximum value in dictionary? 20 answers

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

回答1:

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

or even shorter (from comment):

print max(d, key=d.get)


标签: python max