Python 通过最大值获取字典键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14091636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get dict key by max value
提问by mclafee
I'm trying to get the dict key whose value is the maximum of all the dict's values.
我正在尝试获取其值是所有 dict 值中最大值的 dict 键。
I found two ways, both not elegant enough.
我找到了两种方法,都不够优雅。
d= {'a':2,'b':5,'c':3}
# 1st way
print [k for k in d.keys() if d[k] == max(d.values())][0]
# 2nd way
print Counter(d).most_common(1)[0][0]
Is there a better approach?
有没有更好的方法?
采纳答案by Martijn Pieters
Use the keyparameter to max():
使用key参数max():
max(d, key=d.get)
Demo:
演示:
>>> d= {'a':2,'b':5,'c':3}
>>> max(d, key=d.get)
'b'
The keyparameter takes a function, and for each entry in the iterable, it'll find the one for which the keyfunction returns the highest value.
该key参数需要一个功能,并在迭代的每个条目,它会发现其中的一个key函数返回的最高值。

