Skip to content

Instantly share code, notes, and snippets.

@nicc777
Created March 31, 2023 07:12
Show Gist options
  • Save nicc777/c498739960843714056576ad4fb7309f to your computer and use it in GitHub Desktop.
Save nicc777/c498739960843714056576ad4fb7309f to your computer and use it in GitHub Desktop.
Python deep merge dictionaries

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 the b key, resulting in a merged dictionary with the c key value from dict2 overwriting the c key value from dict1. The e key from dict2 is also added to the merged dictionary. The a and f keys are simply copied over from dict1 and dict2, respectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment