Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

5 maximum values in a python dictionary

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

like image 285
Alejandro Avatar asked Aug 25 '11 21:08

Alejandro


People also ask

How do you find the maximum in a dictionary?

By using max() and dict. get() method we can easily get the Key with maximum value in a dictionary. To obtain the maximum value from the dictionary we can use the in-built max() function. In this example, we can use iterable and dict to get the key paired with the maximum value.

Can you use Max on a dictionary Python?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

Can you have 3 items in a dictionary Python?

You can add as many items as you like.

What is the maximum size of a Python dictionary?

It will not display the output because the computer ran out of memory before reaching 2^27. So there is no size limitation in the dictionary.


2 Answers

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.

like image 127
A. Coady Avatar answered Oct 06 '22 14:10

A. Coady


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

like image 34
Felix Kling Avatar answered Oct 06 '22 15:10

Felix Kling