Using the heap queue algorithm :
import heapq
y = {'a':55, 'b':33, 'c':67, 'd':12}
print heapq.nlargest(n=3, iterable=y, key=y.get)[-1]
This will do better for large dictionaries than sort the entire dict each time. In particular, with a dictionary of items nwhere you are looking for the largest k, this is done in O(n log k)place of O(n log n).
Also note that this gives you all three of the biggest values โโas a list, just delete [-1]:
print heapq.nlargest(n=3, iterable=y, key=y.get)
# ['c', 'a', 'b']
source
share