Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

top values from dictionary

How do I retrive the top 3 list from a dictionary?

>>> d {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4} 

Expected result:

and: 23 only: 21 this: 14 
like image 365
shantanuo Avatar asked Aug 10 '12 13:08

shantanuo


People also ask

How do you find the highest value in a dictionary?

Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.

How do I get a list of unique values from a dictionary?

We can use the dict. fromkeys method of the dict class to get unique values from a Python list. This method preserves the original order of the elements and keeps only the first element from the duplicates.


2 Answers

Use collections.Counter:

>>> d = Counter({'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}) >>> d.most_common() [('and', 23), ('only.', 21), ('this', 14), ('test', 4), ('a', 2), ('is', 2), ('work', 2), ('will', 2), ('as', 2)] >>> for k, v in d.most_common(3): ...     print '%s: %i' % (k, v) ...  and: 23 only.: 21 this: 14 

Counter objects offer various other advantages, such as making it almost trivial to collect the counts in the first place.

like image 89
Martijn Pieters Avatar answered Sep 21 '22 03:09

Martijn Pieters


>>> d = {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4} >>> t = sorted(d.iteritems(), key=lambda x:-x[1])[:3]  >>> for x in t: ...     print "{0}: {1}".format(*x) ...  and: 23 only.: 21 this: 14 
like image 29
Maria Zverina Avatar answered Sep 20 '22 03:09

Maria Zverina