I have the following code that uses a heap to get the dictionary elements with the highest value, but it’s not returning the expected result:
import heapq
import operator
a={'third': 3, 'fourth': 2, 'first': 5, 'second': 4}
heapq.nlargest(4,a,operator.itemgetter(1))
>>['fourth', 'first', 'third', 'second']
Why is it not returning:
>>['first' , 'second' , 'third' , 'fourth']
?
Thanks.
Take a look at what
operator.itemgetter(1)actually does to your dictionary:When you iterate over a dictionary, you iterate over the keys. Since you want the values, use use
a.getto fetch the items:a.get(key)is a method that works likea[key], so it’s essentially doing this:And now your code works: