Recursively Merge Dictionaries in Python
Last Updated :
22 Feb, 2024
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read