4

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?)

Community
  • 1
  • 1
blues
  • 4,547
  • 3
  • 23
  • 39
  • Are `dict`s the only "special" type in the dictionary that you want to combine? – robert May 22 '12 at 14:18
  • @antti: i think for my question there might be an easier solution because the level of nesting (depth) is known beforehand (and in this case is only 2) – blues May 22 '12 at 14:21
  • @robert: yes. just dicts – blues May 22 '12 at 14:23
  • What behavior do you want if my_dict contains a dict for some key but other_dict contains a non-dict (or vice versa). E.g., `my_dict={'a':1}` and `other_dict={'a':{'b':2}}` – Edward Loper May 22 '12 at 14:25

1 Answers1

7
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)

Edward Loper
  • 15,374
  • 7
  • 43
  • 52
  • this will do. the case of conflicting dicts versus strings/ints can't happen with the data i am generating the dicts from. thanks – blues May 22 '12 at 14:28