2 回答

TA贡献1877条经验 获得超1个赞
另一种使用方式collections.Counter:
from collections import Counter
sum(map(Counter, d.values()), Counter())
输出:
Counter({'a': 5, 'b': 10, 'c': 13, 'd': 10})

TA贡献1807条经验 获得超9个赞
您可以使用collections.defaultdict:
from collections import defaultdict
d = {'dicta':{'a':1,'b':2,'c':3}, 'dictb':{'a':2,'b':3,'c':1}, 'dictc':{'a':2,'b':5,'c':9,'d':10}}
_d = defaultdict(int)
for a in d.values():
for c, j in a.items():
_d[c] += j
print(dict(_d))
输出:
{'a': 5, 'b': 10, 'c': 13, 'd': 10}
使用更短的解决方案itertools.groupby:
from itertools import groupby
r = sorted([i for b in d.values() for i in b.items()], key=lambda x:x[0])
result = {a:sum(c for _, c in b) for a, b in groupby(r, key=lambda x:x[0])}
输出:
{'a': 5, 'b': 10, 'c': 13, 'd': 10}
添加回答
举报