Print the key of the max value in a dictionary the

2019-01-23 18:10发布

This question already has an answer here:

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

标签: python max
1条回答
爷的心禁止访问
2楼-- · 2019-01-23 18:37
print max(d.keys(), key=lambda x: d[x]) 

or even shorter (from comment):

print max(d, key=d.get)
查看更多
登录 后发表回答