我有两个像这样构建的dicts:
字典-1:
{A:{'a1':10,'a2':20},B:{'b1':10,'b2':20}}
字典-2:
{A:{'a3':30},B:{'b3':30},C:{'c1':100}}
我想以这种方式结合它们:
{A:{'a1':10,'a2':20,'a3':30},B:{'b1':10,'b2':20,'b3':30},C:{'c1':100}}
答案 0 :(得分:5)
迭代解决方案可能是这样的:
d1 = {'A':{'a1':10,'a2':20},'B':{'b1':10,'b2':20}}
d2 = {'A':{'a3':30},'B':{'b3':30},'C':{'c1':100}}
d3 = {}
for d in [d1, d2]:
for k, v in d.items():
d3.setdefault(k, {}).update(v)
结果
d3 = {'A': {'a1': 10, 'a3': 30, 'a2': 20}, 'C': {'c1': 100}, 'B': {'b1': 10, 'b2': 20, 'b3': 30}}
但它不会对共享密钥中的值进行求和!