如何使用相同的键添加值。在sum(int(v)))
m = {'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}
l = []
for i in m:
#print (i)
for j in i.items():
l.append(j)
from collections import defaultdict
f = defaultdict(list)
for k, v in l:
f[k].append(int(v)) #hack
for i,j in f.items():
print (i,sum(j))
我的生活
Rash 4
Manjeet 5
Akash 7
我的期望值
{'Rash': 4, 'Manjeet': 5, 'Akash': 7}
答案 0 :(得分:1)
您可以使用collections.Counter
作为更简单的方法:
from collections import Counter
c = Counter()
for d in m:
c += d
print(c)
# Counter({'Akash': 7, 'Manjeet': 5, 'Rash': 4})
或使用defaultdict
:
out = defaultdict(int)
for d in m:
for k,v in d.items():
out[k] += v
print(out)
# defaultdict(<class 'int'>, {'Rash': 4, 'Manjeet': 5, 'Akash': 7})