Returning the three maximal values in a dictionary
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)]
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)]
You can use this:
a = {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}
l = sorted(list(a.items()), key=lambda tup: tup[1], reverse=True)[:3]
print(l) # [(19, 244675), (20, 115878), (18, 111490)]
It converts the dictionary a
into a list of tuples, sort by tup[1]
, reverse it and get the first 3 hits.