This question already has answers here:
Closed 3 years ago.
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)
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']