0

my_dict = {'label': 6, 'label_2': 5, 'label_3': 9, 'label_4': 12}

I would like to create a list that will contain the top 2 (or 3, or 4, or 50... this will vary) dictionary keys, according to their highest values. So in the example above if I wanted the top 2, I should get:

['label_3', 'label_4']

for top 3 I should get:

['label', 'label_3', 'label_4']

And so on.

After reading some other stackoverflow threads, I've been experimenting with heapq, but can't get it to work the way I want. Would appreciate some help.

user2390206
  • 123
  • 1
  • 9
  • Possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – DeepSpace Nov 17 '16 at 11:10
  • You can add your solution as an answer instead of editing in to your question. – Lafexlos Nov 17 '16 at 11:11

1 Answers1

0

Of course, the moment I post here, I find a solution (thanks to the heapq documentation). This works:

my_list = heapq.nlargest(3, my_dict, key=my_dict.get)

This will go over my_dict and return the keys with the 3 largest values.

Thanks.

user2390206
  • 123
  • 1
  • 9