字典中的最高值

sha*_*nuo 28 python dictionary

如何从字典中查找前3个列表?

>>> d
{'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
Run Code Online (Sandbox Code Playgroud)

预期结果:

and: 23
only: 21
this: 14
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 41

用途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
Run Code Online (Sandbox Code Playgroud)

计数器对象提供了各种其他优点,例如,首先收集计数几乎是微不足道的.


Mar*_*ina 21

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • 实际上,对于 3 个最高值,我会使用 `heapq.nlargest()` 函数;它比对整个序列进行排序更有效。这就是 `Counter()` 内部使用的内容。 (3认同)
  • 同意 Counter 是更好的方法,如果你也想数数的话。但是,如果您只想要已经创建的 dict 中的前 3 个值,这似乎有点矫枉过正。:) (2认同)