-2

I have two dicts built like this:

Dict-1:

{A:{'a1':10,'a2':20},B:{'b1':10,'b2':20}}

Dict-2:

{A:{'a3':30},B:{'b3':30},C:{'c1':100}}

I want to combine them this way:

{A:{'a1':10,'a2':20,'a3':30},B:{'b1':10,'b2':20,'b3':30},C:{'c1':100}}
olegmil
  • 347
  • 1
  • 4
  • 10

1 Answers1

5

An iterative solution may be this:

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)

results in

d3 = {'A': {'a1': 10, 'a3': 30, 'a2': 20}, 'C': {'c1': 100}, 'B': {'b1': 10, 'b2': 20, 'b3': 30}}

But it doesn't sum values from shared keys!

Don
  • 16,928
  • 12
  • 63
  • 101