2

Is there any generic way to update python dictionary without overwriting the sub-dicts. The dictionaries are dynamically generated hence, cannot predict the level, depth or subkeys in advance.

Consider following two dictionaries are generated dynamically -

d1 = {'a' : { 'b' : 'c'} }
d2 = {'a' : { 'd' : 'e'} }

If I call an update function the result would be something like this d1.update(d2) print d1

Result =

{'a': {'d': 'e'}}

Expected Result =

{'a': {'b': 'c', 'd': 'e'}}

Above dictionaries are just for an example. The dictionaries could be of any level dynamically generated. Hence, provide if any in built function for python.. or some other way.

Corley Brigman
  • 11,633
  • 5
  • 33
  • 40
Ronu
  • 543
  • 1
  • 8
  • 17

2 Answers2

1
def update(d1,d2):
    c = d1.copy()
    for key in d2:
        if key in d1:c[key].update(d2[key])
        else:c[key] = d2[key]
    return c
WeizhongTu
  • 6,124
  • 4
  • 37
  • 51
1

AFAIK there is no built-in for this. You can try something like this:

result = {key : [value, d2[key]] if key in d2 else value 
          for key,value in d1.items()}

Assuming you want a dictionary as a result (expected result in your question is not a valid Python construct).

Or:

result = {key : [value, d2[key]] if key in d2 else [value]
          for key,value in d1.items()}

if you want to always have a list as a value.

To merge nested dicts you can use this one-liner:

result = {key : value.update(d2[key]) or value if key in d2 else value
          for key,value in d1.items()}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130