I have two dictionaries and I want to combine them.
dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}
I want to end up with
{'abc': {'test1': 123, 'test2': 456}}
if dict2 = {'abc': 100}
then I would want:
{'abc' 100}
I tried dict1.update(dict2)
but that gave me {'abc': {'test2': 456}}
Is there a pythonic way to do this?
IIUC, you could do the following:
def recursive_update(d1, d2):
"""Updates recursively the dictionary values of d1"""
for key, value in d2.items():
if key in d1 and isinstance(d1[key], dict) and isinstance(value, dict):
recursive_update(d1[key], value)
else:
d1[key] = value
dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}
recursive_update(dict1, dict2)
print(dict1)
Output
{'abc': {'test1': 123, 'test2': 456}}
Note that the recursion only works for values that are dictionaries. For example:
dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': 100}
produces (as expected):
{'abc': 100}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With