5 maximum values in a python dictionary
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
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.