bek*_*man 4 python sorting dictionary list
我想创建一个finalDic,它包含公共键和值的总和
myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}, ...]
Run Code Online (Sandbox Code Playgroud)
首先找到共同的密钥
commonkey = [{2:1, 3:1}, {2:3, 3:4}, {2:5, 3:6}]
Run Code Online (Sandbox Code Playgroud)
然后按它们的值求和并排序
finalDic= {3:11, 2,9}
Run Code Online (Sandbox Code Playgroud)
我试过这个,甚至没有关闭我想要的东西
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)
Run Code Online (Sandbox Code Playgroud)
谢谢
这是我如何做到的:
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}
Run Code Online (Sandbox Code Playgroud)
或者作为一个疯狂的单行:
{k: sum(d[k] for d in my_dict) for k in reduce(set.intersection, map(set, my_dict))}
Run Code Online (Sandbox Code Playgroud)