How to get the 3 items with the highest value from dictionary? [duplicate]

强颜欢笑 提交于 2020-01-30 09:24:05

问题


Suppose i have this dictionary: {"A":3,"B":4,"H":1,"K":8,"T":0}

I want to get the keys of the highest 3 values (so in this case I will get the keys: K B and A)


回答1:


You may use simple list comprehension expression as:

>>> sorted(my_dict, key=my_dict.get, reverse=True)[:3]
['K', 'B', 'A']

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']


来源:https://stackoverflow.com/questions/40496518/how-to-get-the-3-items-with-the-highest-value-from-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!