5 maximum values in a python dictionary

Alejandro picture Alejandro · Aug 25, 2011 · Viewed 85.5k times · Source

I have a dictionary like this:

A = {'a':10, 'b':843, 'c': 39,.....}

I want to get the 5 maximum values of this dict and store a new dict with this. To get the maximum value I did:

max(A.iteritems(), key=operator.itemgetter(1))[0:]

Perhaps it is an easy task, but I am stuck on it for a long time. Please help!!!

Answer

A. Coady picture A. Coady · Aug 25, 2011

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.