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, \
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])