5 maximum values in a python dictionary

No need to use iteritems and itemgetter. The dict’s own get method works fine.

max(A, key=A.get)

Similarly for sorting:

sorted(A, key=A.get, reverse=True)[:5]

Finally, if the dict size is unbounded, using a heap will eventually be faster than a full sort.

import heapq
heapq.nlargest(5, A, key=A.get)

For more information, have a look at the heapq documentation.

Leave a Comment