top values from dictionary

前端 未结 4 1797
野的像风
野的像风 2020-11-29 07:03

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


        
4条回答
  •  孤街浪徒
    2020-11-29 07:41

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

提交回复
热议问题