I am looking for feedback on my Python code. I am trying to merge two dictionaries. One of the dictionaries controls the structure and the default values, the second dictionary will overwrite the default values when applicable.
Please note that I am looking for the following behaviour:
- keys only present in the other dict should not be added
- nested dicts should be taken into account
I wrote this simple function:
def merge_dicts(base_dict, other_dict):
""" Merge two dicts
Ensure that the base_dict remains as is and overwrite info from other_dict
"""
out_dict = dict()
for key, value in base_dict.items():
if key not in other_dict:
# simply use the base
nvalue = value
elif isinstance(other_dict[key], type(value)):
if isinstance(value, type({})):
# a new dict myst be recursively merged
nvalue = merge_dicts(value, other_dict[key])
else:
# use the others' value
nvalue = other_dict[key]
else:
# error due to difference of type
raise TypeError('The type of key {} should be {} (currently is {})'.format(
key,
type(value),
type(other_dict[key]))
)
out_dict[key] = nvalue
return out_dict
I am sure this can be done more beautifully/pythonic.