Open In App

Recursively Merge Dictionaries in Python

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Merging dictionaries in Python is a common task, but when dealing with nested structures, a straightforward merge may not be sufficient. Recursively merging dictionaries involves combining nested key-value pairs within dictionaries. This process is essential when working with hierarchical data structures. In Python, there are several approaches to achieve recursive dictionary merging, each with its advantages. In this article, we see how we can recursively merge dictionaries in Python.

Recursively Merge Dictionaries in Python

Below, are the methods of Recursively Merge Dictionaries In Python:

Recursively Merge Dictionaries Using a Recursive Function

In this example, the code defines a concise `recursive_merge` function to recursively merge dictionaries, handling nested structures. It iterates through the keys of the second dictionary (`dict2`), merging nested dictionaries if present, and updating non-dictionary values. The example dictionaries `dict1` and `dict2` are merged.

Python3




def recursive_merge(dict1, dict2):
    for key, value in dict2.items():
        if key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict):
            # Recursively merge nested dictionaries
            dict1[key] = recursive_merge(dict1[key], value)
        else:
            # Merge non-dictionary values
            dict1[key] = value
    return dict1
 
# Example dictionaries
dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}
dict2 = {'f': 9, 'c': 6, 'g': 3}
 
# Merge dictionaries recursively
result = recursive_merge(dict1, dict2)
print(result)


Output

{'a': 1, 'b': 2, 'd': 3, 'e': 4, 'f': 9, 'c': 6, 'g': 3}



Recursively Merge Dictionaries In Python Using update Method

In this example, The code merges two dictionaries, `dict1` and `dict2`, recursively updating values in `dict1` with those from `dict2`. It handles nested dictionaries and prints the merged result after updating using `dict1.update(dict2)`. Note: The recursive_merge function call at the end might not have the intended effect due to the prior update.

Python3




def recursive_merge(dict1, dict2):
    for key, value in dict2.items():
        if key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict):
            # Recursively merge nested dictionaries
            recursive_merge(dict1[key], value)
        else:
            # Merge non-dictionary values
            dict1[key] = value
 
# Example dictionaries
dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}
dict2 = {'f': 9, 'c': 6, 'g': 3}
 
# Merge dictionaries recursively
dict1.update(dict2)
recursive_merge(dict1, dict2)
print(dict1)


Output

{'a': 1, 'b': 2, 'd': 3, 'e': 4, 'f': 9, 'c': 6, 'g': 3}



Recursively Merge Dictionaries In Python Using collections.ChainMap Class

In this example, The code uses `ChainMap` from the `collections` module to merge dictionaries `dict1` and `dict2` recursively, creating a merged view stored in the `result` variable, which is then printed.

Python3




from collections import ChainMap
 
# Example dictionaries
dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}
dict2 = {'f': 9, 'c': 6, 'g': 3}
 
# Merge dictionaries recursively using ChainMap
result = dict(ChainMap(dict1, dict2))
print(result)


Output

{'f': 9, 'c': 6, 'g': 3, 'a': 1, 'b': 2, 'd': 3, 'e': 4}



Conclusion

Merging dictionaries recursively in Python can be achieved using various approaches. The choice of method depends on the specific requirements and preferences of the programmer. Whether you prefer a custom recursive function, the update method, or the collections.ChainMap class, these approaches provide flexibility and clarity when dealing with nested dictionaries. Choose the one that best suits your needs in a particular situation.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads