通过最大值获取dict键 [英] Get dict key by max value
本文介绍了通过最大值获取dict键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获得dict键,其中所有dict的值都是最大值。
我发现两种方式都不够优雅。
d = {'a':2,'b' :5,'c':3}
#第一种方式
print [k for d.keys()中的k如果d [k] == max(d.values())] [0]
#第二种方式
打印计数器(d).most_common(1)[0] [0]
有更好的方法吗?
解决方案
使用键
参数到 max()
:
max(d,key = d.get)
演示:
< p $ p>
>>> d = {'a':2,'b':5,'c':3}
>>> max(d,key = d.get)
'b'
key
参数接收一个函数,对于iterable中的每个条目,它会找到 key
函数返回的值最高价值。
I'm trying to get dict key where it's value is max in all dict's values. 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 better approach?
解决方案
Use the key
parameter to max()
:
max(d, key=d.get)
Demo:
>>> d= {'a':2,'b':5,'c':3}
>>> max(d, key=d.get)
'b'
The key
parameter takes a function, and for each entry in the iterable, it'll find the one for which the key
function returns the highest value.
这篇关于通过最大值获取dict键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文