5 maximum values in a python dictionary

PythonDictionaryMax

Python Problem Overview


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!!!

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

You are close. You can sort the list using sorted [docs] and take the first five elements:

newA = dict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])

See also: Python Sorting HowTo

Solution 3 - Python

You could use collections.Counter here:

dict(Counter(A).most_common(5))

Example:

>>> from collections import Counter
>>> A = {'a' : 1, 'b' : 3, 'c' : 2, 'd' : 4, 'e' : 0, 'f' :5}
>>> dict(Counter(A).most_common(5))
{'a': 1, 'c': 2, 'b': 3, 'd': 4, 'f': 5}

Solution 4 - Python

For Python 3

import operator
dict(sorted(A.items(), key=operator.itemgetter(1), reverse=True)[:5])

Solution 5 - Python

Try this:

dict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlejandroView Question on Stackoverflow
Solution 1 - PythonA. CoadyView Answer on Stackoverflow
Solution 2 - PythonFelix KlingView Answer on Stackoverflow
Solution 3 - PythonAkavallView Answer on Stackoverflow
Solution 4 - PythonMalindaView Answer on Stackoverflow
Solution 5 - PythonGerratView Answer on Stackoverflow