识别具有最大键数的值

nek*_*tar 5 python sorting dictionary

我有一个类似这样的词典:

 ip = { "1" : ['a','b'],
      "2" : ['a','c'],
      "3" : ['a','b','c','d'],
      "4" : ['a','b','d','e']}
Run Code Online (Sandbox Code Playgroud)

我需要找到值集中的哪些项目具有最大数量的密钥,并且还按降序列出项目.输出将是这样的:

op = {"a":4,"b":3,"c":2,"d":2,"e":1}
Run Code Online (Sandbox Code Playgroud)

但我在某处读到dict不能排序,所以输出也可以是一个元组:

op = [('a', 4), ('b', 3), ('c', 2), ('d', 2), ('e', 1)]
Run Code Online (Sandbox Code Playgroud)

我们可以遍历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)
Run Code Online (Sandbox Code Playgroud)

有没有比嵌套更快/更好的方法?

sty*_*ane 3

只需使用Counter和chain.from_iterable

In [9]: from collections import Counter

In [10]: from itertools import chain

In [11]: ip = { "1" : ['a','b'],
    ...:       "2" : ['a','c'],
    ...:       "3" : ['a','b','c','d'],
    ...:       "4" : ['a','b','d','e']}

In [12]: Counter(chain.from_iterable(ip.values()))
Out[12]: Counter({'a': 4, 'b': 3, 'c': 2, 'd': 2, 'e': 1})
Run Code Online (Sandbox Code Playgroud)

要删除重复值,您始终可以执行以下操作:

>>> from operator import itemgetter
>>> sorted(Counter(chain.from_iterable(map(set, ip.values()))).items(), key=itemgetter(1), reverse=True)
[('a', 4), ('b', 3), ('c', 2), ('d', 2), ('e', 1)]
Run Code Online (Sandbox Code Playgroud)