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
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.
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.
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.
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With