Returning the three maximal values in a dictionary


I have the following dictionary:

'{0: 0, 1: 11, 2: 26, 3: 43, 4: 14, 5: 29, 6: 34, 7: 49, 8: 49, 9: 108, 10: 124, 11: 108, 12: 361, 13: 290, 14: 2118, 15: 5408, 16: 43473, 17: 109462, 18: 111490, 19: 244675, 20: 115878, 21: 6960}'

And for this dictionary I want write a function that returns the three key-value pairs that have the highest values (So in this case key 18, 19, 20).

I came up with the following:

cachedict = nr_of_objects_per_century() #Dictionary mentioned above

def top_3_centuries():
        max_nr_works_list = sorted(cachedict.values())
        top_3_values = []
        for i in range(len(max_nr_works_list)-3, len(max_nr_works_list)):
            top_3_values.append(max_nr_works_list[i])
            print(top_3_values)

This gives me a list of the max-values I want to lookup. But how do I proceed from here? Is there a way to do this without a reverse-lookup (Which is slow for dictionaries, right?) I have the feeling that I can do this task much more efficiently/pythonic.


Answer

heapq.nlargest

You can avoid a full sort here by using a heap queue:

from heapq import nlargest
from operator import itemgetter

dct = {0: 0, 1: 11, 2: 26, 3: 43, 4: 14, 5: 29, 6: 34, 7: 49, 8: 49,
       9: 108, 10: 124, 11: 108, 12: 361, 13: 290, 14: 2118, 15: 5408,
       16: 43473, 17: 109462, 18: 111490, 19: 244675, 20: 115878, 21: 6960}

res = nlargest(3, dct.items(), key=itemgetter(1))

print(res)
# [(19, 244675), (20, 115878), (18, 111490)]