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

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

Answer

You can simply use sorted() to get the keys of dict as:

my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0}

my_keys = sorted(my_dict, key=my_dict.get, reverse=True)[:3]
# where `my_keys` holds the value:
#     ['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)

most_common = c.most_common(3)  # returns top 3 pairs
# where `most_common` holds the value: 
#     [('K', 8), ('B', 4), ('A', 3)]

# For getting the keys from `most_common`:
my_keys = [key for key, val in most_common]

# where `my_keys` holds the value: 
#     ['K', 'B', 'A']

Attribution
Source : Link , Question Author : Liron Cohen , Answer Author : Moinuddin Quadri

Leave a Comment