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
Solution 1:
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.
Solution 2:
>>> 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
Solution 3:
The replies you already got are right, I would however create my own key function to use when call sorted().
d = {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
# create a function which returns the value of a dictionary
def keyfunction(k):
return d[k]
# sort by dictionary by the values and print top 3 {key, value} pairs
for key in sorted(d, key=keyfunction, reverse=True)[:3]:
print "%s: %i" % (key, d[key])