小编nek*_*tar的帖子

识别具有最大键数的值

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

 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)

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

python sorting dictionary

5
推荐指数
1
解决办法
65
查看次数

标签 统计

dictionary ×1

python ×1

sorting ×1