如何从字典中获取价值最高的3个项目? [英] How to get the 3 items with the highest value from dictionary?
本文介绍了如何从字典中获取价值最高的3个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这本字典: {"A":3,"B":4,"H":1,"K":8,"T":0}
Suppose i have this dictionary: {"A":3,"B":4,"H":1,"K":8,"T":0}
我想获得最高3个值的键(因此在这种情况下,我将获得键:K B和A)
I want to get the keys of the highest 3 values (so in this case I will get the keys: K B and A)
推荐答案
您可以将简单的 list理解表达式用作:
You may use simple list comprehension expression as:
>>> sorted(my_dict, key=my_dict.get, reverse=True)[:3]
['K', 'B', 'A']
或者,您可以使用 collections.Counter()
您也需要价值:
OR, you may use collections.Counter()
if you need value as well:
>>> from collections import Counter
>>> my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0}
>>> c = Counter(my_dict)
>>> mc = c.most_common(3) # returns top 3 values
# content of mc: [('K', 8), ('B', 4), ('A', 3)]
# For getting the keys from "mc":
# >>> [key for key, val in mc]
# ['K', 'B', 'A']
这篇关于如何从字典中获取价值最高的3个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文