我想总结2个dictonaries
inv = {'gold coin': 41, 'rope': 1}
inv2 = {'rope': 3, 'torch': 10}
我用Counter子类
实现了它inv = Counter({'gold coin': 41, 'rope': 1})
inv2 = Counter({'rope': 3, 'torch':10})
result = dict(inv + inv2)
print(result)
输出:
{'gold coin': 41, 'rope': 4, 'torch': 10}
现在我很好奇是否有可能用循环和其他方式对这2个字典进行求和。
有什么想法吗?
答案 0 :(得分:2)
你可以试试这个:
import itertools
inv = {'gold coin': 41, 'rope': 1}
inv2 = {'rope': 3, 'torch': 10}
final_data = [(a, list(b)) for a, b in itertools.groupby(list(inv.items())+list(inv2.items()), key=lambda x:x[0])]
new_final_data = {a:sum(c for i, c in b) for a, b in final_data}
输出:
{'gold coin': 41, 'rope': 4, 'torch': 10}
答案 1 :(得分:2)
你可以使用词典理解 -
print({k: inv.get(k, 0) + inv2.get(k, 0) for k in set(inv) | set(inv2) })
打印 -
{'gold coin': 41, 'rope': 4, 'torch': 10}
答案 2 :(得分:2)
inv = {'gold coin': 41, 'rope': 1}
inv2 = {'rope': 3, 'torch': 10}
result = {val: inv.get(val, 0) + inv2.get(val, 0) for val in set(inv).union(inv2)}
print(result)
输出:
{'torch': 10, 'rope': 4, 'gold coin': 41}
答案 3 :(得分:1)
这是一个更长的方法 with loops ,所以你可以根据需要添加任意数量的dicts
inv = {'gold coin': 41, 'rope': 1,}
inv2 = {'rope': 3, 'torch': 10}
def sum_dicts(*args):
new_dict ={}
for arg in args:
for key, value in arg.items():
if key in new_dict:
new_dict[key] += value
else:
new_dict[key] = value
return new_dict
print(sum_dicts(inv, inv2))