Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python deep merge dictionary data [duplicate]

Tags:

python

Is there a library in Python that I can use to deep merge dictionaries:

The following:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } 

When i combine I want this to look like:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } } 
like image 780
evolution Avatar asked Dec 18 '13 10:12

evolution


1 Answers

I hope I don't reinvent the wheel but the solution is fairly short. And, superfun to code.

def merge(source, destination):     """     run me with nosetests --with-doctest file.py      >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }     >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }     >>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }     True     """     for key, value in source.items():         if isinstance(value, dict):             # get node or create one             node = destination.setdefault(key, {})             merge(value, node)         else:             destination[key] = value      return destination 

So the idea is to copy the source to the destination, and every time it's a dict in the source, recurse. So indeed you will have a bug if in A a given element contains a dict and in B any other type.

[EDIT] as said in comments the solution was already here : https://stackoverflow.com/a/7205107/34871

like image 88
vincent Avatar answered Oct 14 '22 03:10

vincent