Nih*_*ngi 8 python dictionary ordereddictionary
我有一个OrderedDict按值排序的有序字典().如何获得最高(例如25个)键值并将它们添加到新词典中?例如:我有这样的事情:
dictionary={'a':10,'b':20,'c':30,'d':5}
ordered=OrderedDict(sorted(dictionary.items(), key=lambda x: x[1],reverse=True))
Run Code Online (Sandbox Code Playgroud)
现在ordered是一个有序的字典,我想创建一个字典,比如通过获取前2个最频繁的项目及其键:
frequent={'c':30,'b':20}
Run Code Online (Sandbox Code Playgroud)
Ben*_*kin 15
OrderedDict的主要目的是保留元素的创建顺序.你想要的是collections.OrderedDict,它内置了n个最常用的功能:
>>> dictionary={'a':10,'b':20,'c':30,'d':5}
>>> import collections
>>> collections.Counter(dictionary).most_common(2)
[('c', 30), ('b', 20)]
Run Code Online (Sandbox Code Playgroud)
只需使用您已经拥有的(反向)顺序字典中的前N个项(密钥对)来制作新字典。例如,要获得前三项,您可以执行以下操作:
from collections import OrderedDict
from operator import itemgetter
# create dictionary you have
dictionary = {'a': 10, 'b': 20, 'c': 30, 'd': 5}
ordered = OrderedDict(sorted(dictionary.items(), key=itemgetter(1), reverse=True))
topthree = dict(ordered.items()[:3])
print(topthree) # -> {'a': 10, 'c': 30, 'b': 20}
Run Code Online (Sandbox Code Playgroud)
对于Python 3,可以使用dict(list(ordered.items())[:3])因为items()在该版本中返回迭代器。另外,您可以使用dict(itertools.islice(ordered.items(), 3))在Python 2和3中都可以使用的方法。
还要注意,结果只是问题中指定的常规词典,而不是a collections.Counter或其他类型的映射。这种方法非常通用,不需要原始dictionary值具有整数值,只要可以排序即可(即通过key函数进行比较)。
| 归档时间: |
|
| 查看次数: |
10833 次 |
| 最近记录: |