Python, merge multi-level dictionaries

dictionary, python

Solution

import collections # requires Python 2.7 -- see note below if you're using an earlier version
def merge_dict(d1, d2):
    """
    Modifies d1 in-place to contain values from d2.  If any value
    in d1 is a dictionary (or dict-like), *and* the corresponding
    value in d2 is also a dictionary, then merge them in-place.
    """
    for k,v2 in d2.items():
        v1 = d1.get(k) # returns None if v1 has no value for this key
        if ( isinstance(v1, collections.Mapping) and 
             isinstance(v2, collections.Mapping) ):
            merge_dict(v1, v2)
        else:
            d1[k] = v2

If you're not using Python 2.7+, then replace `isinstance(v, collections.Mapping)` with `isinstance(v, dict)` (for strict typing) or `hasattr(v, "items")` (for duck typing).

Note that if there's a conflict for some key -- i.e., if d1 has a string value and d2 has a dict value for that key -- then this implementation just keeps the value from d2 (similar to `update`)

Problem

Possible Duplicate: python: Dictionaries of dictionaries merge ``` my_dict= {'a':1, 'b':{'x':8,'y':9}} other_dict= {'c':17,'b':{'z':10}} my_dict.update(other_dict) ``` results in: ``` {'a': 1, 'c': 17, 'b': {'z': 10}} ``` but i want this: ``` {'a': 1, 'c': 17, 'b': {'x':8,'y':9,'z': 10}} ``` How can i do this? (possibly in a simple way?)

Original source

Related problems