October 13, 2024

How to Merge Two Dictionaries in Python

In Python, merging two dictionaries involves combining their key-value pairs into a single dictionary. There are several ways to merge dictionaries, depending on the Python version you’re using and the specific requirements of your task.

Method 1: Using the update() Method

The update() method allows you to merge one dictionary into another. This method modifies the dictionary in place by adding key-value pairs from another dictionary. If there are duplicate keys, the values from the second dictionary will overwrite the values in the first dictionary.

Example:

# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merge dict2 into dict1
dict1.update(dict2)

# dict1 is now updated
print(dict1)
    

Output:

{'a': 1, 'b': 3, 'c': 4}
    

Method 2: Using the | Operator (Python 3.9+)

In Python 3.9 and later, you can use the | operator to merge two dictionaries. This creates a new dictionary without modifying the original ones.

Example:

# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merge using the | operator
merged_dict = dict1 | dict2

# merged_dict contains the merged content
print(merged_dict)
    

Output:

{'a': 1, 'b': 3, 'c': 4}
    

Method 3: Using Dictionary Unpacking (**)

Dictionary unpacking allows you to merge two or more dictionaries by using the ** operator. This creates a new dictionary by combining the key-value pairs from the provided dictionaries.

Example:

# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merge using dictionary unpacking
merged_dict = {**dict1, **dict2}

# merged_dict contains the merged content
print(merged_dict)
    

Output:

{'a': 1, 'b': 3, 'c': 4}
    

Method 4: Using a Loop

You can also merge two dictionaries using a loop to iterate over the key-value pairs and add them to a new dictionary. This method gives you more control over the merging process.

Example:

# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Initialize a new dictionary
merged_dict = {}

# Add key-value pairs from dict1
for key, value in dict1.items():
    merged_dict[key] = value

# Add key-value pairs from dict2
for key, value in dict2.items():
    merged_dict[key] = value

# merged_dict contains the merged content
print(merged_dict)
    

Output:

{'a': 1, 'b': 3, 'c': 4}
    

Method 5: Using the collections.ChainMap (Advanced)

The collections.ChainMap class from the collections module allows you to combine multiple dictionaries into a single view. This is especially useful if you want to work with multiple dictionaries as if they were one, without actually merging them.

Example:

from collections import ChainMap

# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Combine dictionaries using ChainMap
combined = ChainMap(dict1, dict2)

# Accessing values in the combined view
print(combined['a'])  # Output: 1
print(combined['b'])  # Output: 2
print(combined['c'])  # Output: 4
    

Note that in a ChainMap, if the same key exists in multiple dictionaries, the value from the first dictionary is used.

Conclusion

Merging dictionaries in Python can be done in several ways, each with its own advantages. For most use cases, the update() method or the | operator (in Python 3.9+) will be the most straightforward options. For more advanced use cases, dictionary unpacking, loops, and ChainMap offer additional flexibility.