Open In App

Python Merge Two Dictionaries Repeated

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:

  1. Using Recursion
  2. Using collections.ChainMap() Function
  3. 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.






def merge_dicts_recursive(dict1, dict2):
     
    # Iterate through key-value pairs in 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
 
 
# Example usage:
dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}
dict2 = {'f': 9, 'c': 6, 'g': 3}
 
# Merge the dictionaries
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.




import collections
 
def merge_dicts_chainmap(dict1, dict2):
    
    merged_chainmap = collections.ChainMap({}, dict1, dict2)
     
    merged_dict = dict(merged_chainmap)
     
    return merged_dict
 
# Example usage:
dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}
dict2 = {'f': 9, 'c': 6, 'g': 3}
 
# Merge the dictionaries
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.




import collections
 
def merge_dicts_defaultdict(dict1, dict2):
     
    # Create a defaultdict with the default value being an empty dictionary
    merged = collections.defaultdict(dict)
     
    # Iterate over the union of keys from dict1 and dict2
    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]
     
    # Convert the defaultdict to a regular dictionary
    return dict(merged)
 
# Example usage:
dict1 = {'a': 1, 'b': 2, 'd': 3, 'e': 4}
dict2 = {'f': 9, 'c': 6, 'g': 3}
 
# Merge the dictionaries
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}

Article Tags :