Info Question to chatGPT 4:
python deep merge two dictionaries
Response:
def deep_merge_dicts(dict1, dict2):
"""
Recursively merge two dictionaries.
"""
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge_dicts(result[key], value)
else:
result[key] = value
return result
More details:
This function takes two dictionaries as input and returns a new dictionary that is the result of merging the two dictionaries. If a key exists in both dictionaries and the value for that key is a dictionary, the function recursively merges the two dictionaries. Otherwise, the value from the second dictionary overwrites the value from the first dictionary.
Here's an example usage:
dict1 = {'a': 1, 'b': {'c': 2, 'd': 3}}
dict2 = {'b': {'c': 4, 'e': 5}, 'f': 6}
merged_dict = deep_merge_dicts(dict1, dict2)
print(merged_dict)
# Output: {'a': 1, 'b': {'c': 4, 'd': 3, 'e': 5}, 'f': 6}
In this example, the
b
key exists in both dictionaries and has a dictionary value. The function recursively merges the two dictionaries for theb
key, resulting in a merged dictionary with thec
key value fromdict2
overwriting thec
key value fromdict1
. Thee
key fromdict2
is also added to the merged dictionary. Thea
andf
keys are simply copied over fromdict1
anddict2
, respectively.