Python Merge Two Dictionaries Repeated
Last Updated :
07 Mar, 2024
We are given two dictionaries and our task is to merge the two dictionaries using recursion in Python. In this article, we will see how we can merge two dictionaries recursively in Python.
Example:
Input: dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}, dict2 = {'f': 9, 'c': 6, 'g': 3}
Output: {'a': 1, 'b': 2, 'd': 3, 'e': 4, 'f': 9, 'c': 6, 'g': 3}
Explanation: Two dictionaries are merged into a single dictionary.
Merge Two Dictionaries in Python
Below are some of the ways by which we can merge two dictionaries recursively in Python:
- Using Recursion
- Using collections.ChainMap() Function
- Using collections.defaultdict() Function
Merge Two Dictionaries Using Recursion
In this example, the merge_dicts_recursive
function recursively merges two dictionaries (dict1
and dict2
), combining their key-value pairs. If a key exists in both dictionaries and the corresponding values are also dictionaries, the function recursively merges those nested dictionaries. The final merged dictionary is printed after combining the provided dict1
and dict2
.
Python3
def merge_dicts_recursive(dict1, dict2):
for key, value in dict2.items():
if key in dict1 and isinstance (dict1[key], dict ) and isinstance (value, dict ):
merge_dicts_recursive(dict1[key], value)
else :
dict1[key] = value
return dict1
dict1 = { 'a' : 1 , 'b' : 2 , 'd' : 3 , 'e' : 4 }
dict2 = { 'f' : 9 , 'c' : 6 , 'g' : 3 }
merged_dict = merge_dicts_recursive(dict1, dict2)
print (merged_dict)
|
Output
{'a': 1, 'b': 2, 'd': 3, 'e': 4, 'f': 9, 'c': 6, 'g': 3}
Merge Two Dictionaries Using collections.ChainMap() Function
Alternatively, we can build a single view of several mappings by using the ‘collections.ChainMap‘ class. Instead of changing the original dictionaries, we can create a combined view by building a ‘ChainMap’ containing the dictionaries to be merged.
Python3
import collections
def merge_dicts_chainmap(dict1, dict2):
merged_chainmap = collections.ChainMap({}, dict1, dict2)
merged_dict = dict (merged_chainmap)
return merged_dict
dict1 = { 'a' : 1 , 'b' : 2 , 'd' : 3 , 'e' : 4 }
dict2 = { 'f' : 9 , 'c' : 6 , 'g' : 3 }
merged_dict = merge_dicts_chainmap(dict1, dict2)
print (merged_dict)
|
Output
{'f': 9, 'c': 6, 'g': 3, 'a': 1, 'b': 2, 'd': 3, 'e': 4}
Merge Two Dictionaries Using collections.defaultdict() Function
In this example, the merge_dicts_defaultdict
function merges two dictionaries (dict1
and dict2
) using a defaultdict
from the collections
module. It creates a default dictionary with the default value being an empty dictionary, allowing seamless merging even when encountering nested dictionaries. The final merged dictionary is printed after combining the provided dict1
and dict2
.
Python3
import collections
def merge_dicts_defaultdict(dict1, dict2):
merged = collections.defaultdict( dict )
for key in set (dict1) | set (dict2):
if key in dict1 and key in dict2:
if isinstance (dict1[key], dict ) and isinstance (dict2[key], dict ):
merged[key] = merge_dicts_defaultdict(dict1[key], dict2[key])
else :
merged[key] = dict2[key]
elif key in dict1:
merged[key] = dict1[key]
else :
merged[key] = dict2[key]
return dict (merged)
dict1 = { 'a' : 1 , 'b' : 2 , 'd' : 3 , 'e' : 4 }
dict2 = { 'f' : 9 , 'c' : 6 , 'g' : 3 }
merged_dict = merge_dicts_defaultdict(dict1, dict2)
print (merged_dict)
|
Output
{'c': 6, 'd': 3, 'g': 3, 'f': 9, 'e': 4, 'b': 2, 'a': 1}
Share your thoughts in the comments
Please Login to comment...