从python字典获取最高键 [英] Getting the highest key from python dictionary
本文介绍了从python字典获取最高键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带值的python字典,我需要搜索最大键.
I have a python dictionary with values and I need to search the maximum key.
data={'A': 1,'C': 3, 'H': 1,'I': 1, 'B': 1,'J': 2,'S': 1, 'D': 3, 'N': 2}
我尝试max(data, key=data.get)
.这给出了C
的答案.但是我想获得C
& D
作为答案,因为C和D都是最高的数字.
I try max(data, key=data.get)
.This gives the C
as an answer.But I'd like to get C
& D
as an answer,since both C and D are the highest number.
如何在Python中完成此操作?
How this can be done in Python?
推荐答案
单独使用max
不能完成此操作,因为max
仅返回单个元素.相反,首先从data
获取max
值,然后过滤具有相同值的那些键.
You can not do this with max
alone, as max
will only return a single element. Instead, first, get the max
value from data
, then filter those keys that have the same value.
>>> data={'A': 1, 'T': 1, 'C': 3, 'H': 1, 'I': 1, 'B': 1, 'O': 1,'J': 2, 'Q': 1, 'S': 1, 'D': 3, 'N': 2}
>>> max_val = max(data.values())
>>> [key for key, val in data.items() if val == max_val]
['C', 'D']
这篇关于从python字典获取最高键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文