1

I want to merge two dictionary in python with same keys

The dictionary:

dict1 = { 'a1': { 'b1': { 'c1': 'd1' }}}

dict2 = { 'a1': { 'b1': { 'c2': 'd2' }}}

dict3 = { 'a1': { 'b2': { 'c3': 'd3' }}}

dict4 = { 'a2': { 'b3': { 'c4': 'd4' }}}

I want this to merge into

dict1 = {'a1': {'b1': {'c1': 'd1', 'c2': 'd2'}, 'b2': {'c3': 'd3'}},
         'a2': {'b3': {'c4': 'd4'}}}

I have tried merging with update but it is overwriting everything

Thanks in Advance.

EDIT:

The code I tried:

dict1.update(dict2)
dict1.update(dict3)
dict1.update(dict4)

Output:

>>> dict1
{'a1': {'b1': {'c2': 'd2'}}, 'a2': {'b3': {'c4': 'd4'}}}
Dictionar2
  • 49
  • 3

1 Answers1

0

The problem is update only works at the top level.

def addin( d1, d2 ):
    for k,v in d2.items():
        if k not in d1:
            d1[k] = v
        else:
            addin( d1[k], v )

merged = {}
addin( merged, dict1 )
addin( merged, dict2 )
addin( merged, dict3 )
addin( merged, dict4 )
print(merged)
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101