Add script for merging dictionaries

This commit is contained in:
adamoutler 2023-02-13 23:33:02 +00:00
parent 4b8e4f9846
commit a6469184fb

View File

@ -0,0 +1,33 @@
"""This module contains the merge_dict function."""
from functools import reduce
def merge_dict_no_overwrite(base_dictionary, other_dictionary, location=None)->dict:
""" This function merges two dictionaries. If the same key exists in both dictionaries,
the value from the other_dictionary will be used. This function will recurse into nested
dictionaries. If the same key exists in both dictionaries, and the value is a dictionary,
the function will recurse into the nested dictionary. If the same key exists in both dictionaries,
and the value is not a dictionary, the value from the base_dictionary will be used.
Parameters:
base_dictionary: The dictionary to merge the other_dictionary into.
other_dictionary: The dictionary to merge keys from. if the same key exists in both dictionaries,
the value from the base_dictionary will be used.
location: leave blank. This is used to track the location of the key in the dictionary.
Returns:
The merged dictionary.
"""
if location is None:
location=[]
for key in other_dictionary:
if key in base_dictionary:
if isinstance(base_dictionary[key], dict) and isinstance(other_dictionary[key], dict):
merge_dict_no_overwrite(base_dictionary[key], other_dictionary[key],[str(key)])
else:
pass
else:
base_dictionary[key] = other_dictionary[key]
return base_dictionary