以pythonic方式在字典中打印最大值的键 [英] Print the key of the max value in a dictionary the pythonic way

查看:101
本文介绍了以pythonic方式在字典中打印最大值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个字典d,其中键值对包括一个字符串作为键和一个整数作为值,我想在键值字符串中打印出最大的值.

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.

当然,我可以循环遍历d.items(),存储最大值及其键,并在for循环之后输出后者.但是,仅使用像这样的max函数构造,是否还有更多的"pythonic"方式

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

推荐答案

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

或更短(摘自评论):

print max(d, key=d.get)

这篇关于以pythonic方式在字典中打印最大值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆