Python, merge multilevel dictionaries

Possible duplicate:
python: Dictionary dictionary combined

my_dict= {'a':1, 'b':{'x':8,'y':9}} other_dict= {'c':17,'b':{'z':10}} my_dict.update(other_dict) 

leads to:

 {'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? (maybe in a simple way?)

+4
source share
1 answer
 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 are not using Python 2.7+, replace isinstance(v, collections.Mapping) with isinstance(v, dict) (for strict printing) or hasattr(v, "items") (for duck input).

Note that if there is a conflict for some key - that is, if d1 has a string value, and d2 has a dict value for this key - then this implementation simply saves the value from d2 (similar to update )

+5
source

Source: https://habr.com/ru/post/1413763/


All Articles