Python deep merge dictionary data

Question:

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' } } }
Asked By: evolution

||

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

Answered By: vincent
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.