如何在字典列表中找到公用键并按值对它们进行排序? [英] How to find common keys in a list of dicts and sort them by value?
本文介绍了如何在字典列表中找到公用键并按值对它们进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个finalDic,其中包含公用密钥及其值的总和
I want to create a finalDic which contains common keys and sum of their values
myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}, ...]
首先找到公用密钥
commonkey = [{2:1, 3:1}, {2:3, 3:4}, {2:5, 3:6}]
然后求和并按值排序
finalDic= {3:11, 2,9}
我已经尝试过了,甚至没有关闭我想要的东西
I've tried this and not even close what i want
import collections
myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]
def commonKey(x):
i=0
allKeys = []
while i<len(x):
for key in x[0].keys():
allKeys.append(key)
i=i+1
commonKeys = collections.Counter(allKeys)
commonKeys = [i for i in commonKeys if commonKeys[i]>len(x)-1]
return commonKeys
print commonKey(myDic)
谢谢
推荐答案
这是我的处理方式:
my_dict = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]
# Finds the common keys
common_keys = set.intersection(*map(set, my_dict))
# Makes a new dict with only those keys and sums the values into another dict
summed_dict = {key: sum(d[key] for d in my_dict) for key in common_keys}
或者作为疯狂的单线客:
Or as a crazy one-liner:
{k: sum(d[k] for d in my_dict) for k in reduce(set.intersection, map(set, my_dict))}
这篇关于如何在字典列表中找到公用键并按值对它们进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文