top values from dictionary

前端 未结 4 1793
野的像风
野的像风 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 08:01

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

提交回复
热议问题