本文介绍了字典的顶级值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从字典中取出前3名?

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, 'as': 2, 'test': 4}

预期结果:

and: 23
only: 21
this: 14


推荐答案

使用:

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

这篇关于字典的顶级值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:48