top values from dictionary

前端 未结 4 1779
野的像风
野的像风 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:50

    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.

提交回复
热议问题