【发布时间】:2017-06-07 01:47:33
【问题描述】:
我有一个类似这样的字典:
ip = { "1" : ['a','b'],
"2" : ['a','c'],
"3" : ['a','b','c','d'],
"4" : ['a','b','d','e']}
我需要找出值集中的哪些项目对它们有最大数量的键,并且还需要按降序列出项目。输出将类似于:
op = {"a":4,"b":3,"c":2,"d":2,"e":1}
但我在某处读到 dict 不能以排序方式,所以输出也可以是一个元组:
op = [('a', 4), ('b', 3), ('c', 2), ('d', 2), ('e', 1)]
我们可以遍历 dict 并为值集中的每个项目递增该项目的 defaultdict 中的结果。
op = defaultdict(int)
for k,v in ip.iteritems():
for item in v:
op[item]+=1
op = sorted(op.items(), key=lambda x: x[1], reverse=True)
有没有比嵌套 for 更快/更好的方法?
【问题讨论】:
-
您能否提供示例的预期输出?
-
添加了所需的输出..
-
有一个有序字典这种东西...
from collections import OrderedDict.
标签: python sorting dictionary