如何在字典中获取多个最大键值? [英] How to get multiple max key values in a dictionary?
本文介绍了如何在字典中获取多个最大键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一本字典:
data = {'a':1, 'b':2, 'c': 3, 'd': 3}
我想获取字典中的最大值.到目前为止,我一直在做:
I want to get the maximum value(s) in the dictionary. So far, I have been just doing:
max(zip(data.values(), data.keys()))[1]
但我知道我可能会错过另一个最大值.解决这个问题的最有效方法是什么?
but I'm aware that I could be missing another max value. What would be the most efficient way to approach this?
推荐答案
根据您的示例,您似乎正在寻找映射到最大值的键.可以使用列表理解:
Based on your example, it seems like you're looking for the key(s) which map to the maximum value. You could use a list comprehension:
[k for k, v in data.items() if v == max(data.values())]
# ['c', 'd']
如果你有一个很大的字典,把它分成两行,以避免为尽可能多的项目计算最大值:
If you have a large dictionary, break this into two lines to avoid calculating max for as many items as you have:
mx = max(data.values())
[k for k, v in data.items() if v == mx]
在 Python 2.x 中,您将需要 .iteritems()
.
In Python 2.x you will need .iteritems()
.
这篇关于如何在字典中获取多个最大键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文