Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 987
Liron Cohen Avatar asked Nov 08 '16 21:11

Liron Cohen


Video Answer


1 Answers

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']
like image 159
Moinuddin Quadri Avatar answered Sep 19 '22 15:09

Moinuddin Quadri