0
 {255:
     {255:
         {1:
            {2:{}
            }
         }
     }
 },
 {255:
     {255:
         {2:
           {3:{}
           }
         }
     }
 }

My dictionary is highly complex (even more entries than shown above)

Now I want to merge two dictionaries

output should be :

 {255:
     {255:
         {1:
            {2:{}
            }
         },
        {2:
           {3:{}
        }
     }
 }

also the maximum nesting possible is till level 5.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mobman
  • 89
  • 1
  • 8
  • Is there any chance of key collisions? If so, how should they be resolved? Are there non-dictionary values at any point, or are the innermost items always empty dictionaries? – Blckknght Sep 25 '14 at 08:02

2 Answers2

2

Not sure if I understood, but how about this:

def merge(a, b):
    for x in b:
        if x in a:
            merge(a[x], b[x])
        else:
            a[x] = b[x]
    return a
georg
  • 211,518
  • 52
  • 313
  • 390
  • I would initially have thought that `update` one dict with the other would lead to the same results. – Peter Lustig Sep 25 '14 at 08:21
  • Maybe this answer about recursively merging dicts is helpful: http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge – Peter Lustig Sep 25 '14 at 08:23
1

Here's a simple variation on georg's answer that doesn't clobber either of the argument values (it returns a copies of the data in new dictionaries, rather than reusing the existing ones):

import copy

def merge(a, b, copy_a=True):
    if copy_a:
        a = copy.deepcopy(a)
    for x in b:
        if x in a:
            merge(a[x], b[x], copy_a=False)
        else:
            a[x] = copy.deepcopy(b[x])
    return a

The extra argument is used to make the code copy the first dictionary on the first call, but not on any of the recursive calls (since they've already been copied by then). It's an implementation detail, and you would always use the default when calling it from other code.

Blckknght
  • 100,903
  • 11
  • 120
  • 169