I have multiple nested dictionaries of varying depth.
A dictionary can contain a list which in itself can contain further nested dictionaries.
A dictionary can also contain a "leaf-list" which is simply a list with values.
The order of the list elements does not matter.
base_d = {'level 1' : {'level 2': [{'level 3': [1,2,3], 'level 4': {'level 6': 'replace_me'} } ] } } update_d = {'level 1' : {'level 2': [{'level 4': {'level 6': 'new_value','level 7':456},'level 5':123 , 'level 3': [1,2,3,4] }] } }
I want to update all values in base_d
with the values inside update_d
so that the output dictionary becomes
new_d = {'level 1' : {'level 2': [{'level 3': [1,2,3,4], 'level 4': {'level 6': 'new_value'} } ] } }
I have looked into the pydantic.utils.deep_update
library and also tried the following solution inside Update value of a nested dictionary of varying depth
import collections
def update(orig_dict, new_dict):
for key, val in new_dict.iteritems():
if isinstance(val, collections.abc.Mapping):
tmp = update(orig_dict.get(key, { }), val)
orig_dict[key] = tmp
elif isinstance(val, list):
orig_dict[key] = (orig_dict.get(key, []) + val)
else:
orig_dict[key] = new_dict[key]
return orig_dict
But none seem to be able to deal with nested dictionaries inside a list.
from pydantic.utils import deep_update
deep_update(base_d,update_d)
{'level 1': {'level 2': [{'level 4': {'level 6': 'new_value', 'level 7': 456}, 'level 5': 123, 'level 3': [1, 2, 3, 4]}]}}
So how would I be able to update values when I can have lists of nested dictionaries at generic depth inside the base_d and update_d?