Thanks in part to the answers here, I was able to come up with a solution for adding items to a dictionary, including adding items to list values within the dictionary if they are not already in the list.
Python 3:
import collections.abc
def dict_update(d, u, fixed=False):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
if k in d.keys() or not fixed:
d[k] = dict_update(d.get(k, {}), v, fixed=fixed)
elif isinstance(v, list):
if k in d.keys() or not fixed:
# Iterate through list value and add item if not already in list
for i in v:
if i not in d.get(k, []):
d[k] = d.get(k, []) + [i]
else:
if k in d.keys() or not fixed:
d[k] = v
return d
dictionary1 = {
"level1": {
"level2": {"levelA": 0, "levelB": 1},
"level3": ["itemA", "itemB"]
}
}
update = {
"level1": {
"level2": {"levelB": 10},
"level3": ["itemC"]
}
}
updated_dict = dict_update(dictionary1, update, fixed=False)
print(updated_dict)
>>> {'level1': {'level2': {'levelA': 0, 'levelB': 10}, 'level3': ['itemA', 'itemB', 'itemC']}}
If fixed=True
, the input dictionary d
will be fixed and values will only be updated if the keys are already present in the original dict, so new keys will not be added.