18

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Liron Cohen
  • 321
  • 1
  • 3
  • 6
  • 1
    using `d = {"A":3,"B":4,"H":1,"K":8,"T":0}`, you can do `dict(sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[:3]).keys()`, prints `['A', 'K', 'B']` – chickity china chinese chicken Nov 08 '16 at 21:24
  • 4
    Not quite a duplicate -- this question asks for the 3 (or N) largest, the other question answers getting the entire dict ordered by value. You can get the N largest more efficiently by using `heapq.nlargest` in many cases: `import heapq; heapq.nlargest(3, my_dict, key=my_dict.get)`. – Ben Hoyt Nov 08 '16 at 21:56
  • Wonder if this can be extended to cover the case of `getting middle 3 items` easier? Just curious. – Daniel Hao Jan 28 '21 at 19:32

1 Answers1

32

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']
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126