Returning the three maximal values in a dictionary

  • A+
Category:Languages

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, but I can't figure out how.

 


You could also use collections.Counter with most_common (which internally uses a heap queue):

from collections import Counter  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}  count = Counter(dct) print(count.most_common(3))  # [(19, 244675), (20, 115878), (18, 111490)] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: