获得从排序字典到另一个的第一个N个键对 [英] Get first N key pairs from an Ordered Dictionary to another one

查看:114
本文介绍了获得从排序字典到另一个的第一个N个键对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按值排序的有序字典( OrderedDict )。如何获得顶级(如25)键值并将其添加到新字典?
例如:我有这样的东西:

I have an ordered dictionary (OrderedDict) sorted by value. How can I get the top (say 25) key values and add them to a new dictionary? For example: I have something like this:

dictionary={'a':10,'b':20,'c':30,'d':5}
ordered=OrderedDict(sorted(dictionary.items(), key=lambda x: x[1],reverse=True))

现在已订购是一个有序字典,我想创建一个字典说,通过获取前2个最频繁的项目和他们的键:

Now ordered is an ordered dictionary, I want to create a dictionary, say by taking the top 2 most-frequent items and their keys:

frequent={'c':30,'b':20}


推荐答案

OrderedDict的主要目的是保留创建元素的顺序。
你想要的是 collections.Counter ,内置了最常见的功能:

The primary purpose of OrderedDict is retaining the order in which the elements were created. What you want here is collections.Counter, which has the n-most-frequent functionality built-in:

>>> dictionary={'a':10,'b':20,'c':30,'d':5}
>>> import collections
>>> collections.Counter(dictionary).most_common(2)
[('c', 30), ('b', 20)]

这篇关于获得从排序字典到另一个的第一个N个键对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆