Merge two Dictionaries in Python
In Python, the merging of two dictionaries refers to combining two dictionaries’ key-value pairs into one dictionary. When common keys are present in both dictionaries, the values in the second dictionary will overwrite those in the first dictionary in the merged result. Python provides several ways to do this, depending on the version you’re using. Below is a detailed explanation of each method:
1. Using the update() Method
The update() method merges one dictionary into another by adding or updating key-value pairs. This modifies the original dictionary in-place.
# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Merging using update()
dict1.update(dict2)
# Outputs
print("Merged dict1:", dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict2 remains unchanged:", dict2) # Output: {'b': 3, 'c': 4}
Output:
Merged dict1: {'a': 1, 'b': 3, 'c': 4}
dict2 remains unchanged: {'b': 3, 'c': 4}
Explanation:
- The key-value pairs in
dict2are added todict1. - If there is a common key in the two dictionaries (say
'b'), thendict2value will overwritedict1. - The
update()method does not create a new dictionary; it modifiesdict1.
2. Using the | Operator (Python 3.9+)
The | operator combines two dictionaries into a new dictionary, leaving the originals unchanged.
# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Merging using | operator
merged_dict = dict1 | dict2
# Outputs
print("Merged dictionary:", merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict1 remains unchanged:", dict1) # Output: {'a': 1, 'b': 2}
print("dict2 remains unchanged:", dict2) # Output: {'b': 3, 'c': 4}
Output:
Merged dictionary: {'a': 1, 'b': 3, 'c': 4}
dict1 remains unchanged: {'a': 1, 'b': 2}
dict2 remains unchanged: {'b': 3, 'c': 4}
Explanation:
- The
|operator creates a new dictionary calledmerged_dict. - It overwrites values from the left dictionary,
dict1, with values from the right dictionary,dict2, when duplicate keys are found.
3. Using Dictionary Comprehension
This method uses the unpacking operator (**) to combine dictionaries into a new dictionary. The originals remain unchanged.
# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Merging using dictionary comprehension
merged_dict = {**dict1, **dict2}
# Outputs
print("Merged dictionary:", merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict1 remains unchanged:", dict1) # Output: {'a': 1, 'b': 2}
print("dict2 remains unchanged:", dict2) # Output: {'b': 3, 'c': 4}
Output:
Merged dictionary: {'a': 1, 'b': 3, 'c': 4}
dict1 remains unchanged: {'a': 1, 'b': 2}
dict2 remains unchanged: {'b': 3, 'c': 4}
Explanation:
- The
**operator unpacks the key-value pairs from each dictionary. - Duplicate keys are treated just like the
|operator: values from the second dictionary overwrite those of the first.
4. Using collections.ChainMap
ChainMap combines multiple dictionaries into a single view without creating a new dictionary. It prioritizes values from the first dictionary added.
from collections import ChainMap
# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Merging using ChainMap
merged = ChainMap(dict2, dict1)
# Outputs
print("ChainMap merged view:", dict(merged)) # Output: {'b': 3, 'c': 4, 'a': 1}
print("Original dictionaries remain unchanged:")
print("dict1:", dict1) # Output: {'a': 1, 'b': 2}
print("dict2:", dict2) # Output: {'b': 3, 'c': 4}
Output:
ChainMap merged view: {'b': 3, 'c': 4, 'a': 1}
Original dictionaries remain unchanged:
dict1: {'a': 1, 'b': 2}
dict2: {'b': 3, 'c': 4}
Explanation:
ChainMap(dict2, dict1)combinesdict2anddict1into a single view.- If a key exists in both dictionaries, the value from the first dictionary (
dict2) takes precedence.
5. Using a For Loop
Manually merge dictionaries by iterating through one dictionary and adding its items to another.
# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Merging using a for loop
merged_dict = dict1.copy() # Start with a copy of dict1
for key, value in dict2.items():
merged_dict[key] = value
# Outputs
print("Merged dictionary:", merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict1 remains unchanged:", dict1) # Output: {'a': 1, 'b': 2}
print("dict2 remains unchanged:", dict2) # Output: {'b': 3, 'c': 4}
Output:
Merged dictionary: {'a': 1, 'b': 3, 'c': 4}
dict1 remains unchanged: {'a': 1, 'b': 2}
dict2 remains unchanged: {'b': 3, 'c': 4}
Explanation:
- A copy of
dict1makes sure the original dictionary is not altered. - A
forloop runs over the elements indict2and appends them tomerged_dict. - If keys overlap, values from
dict2overwrite those indict1.
Full Comparison Table
| Method | Creates New Dictionary? | Modifies Original? | Handles Duplicate Keys? | Python Version |
|---|---|---|---|---|
update() | No | Yes (dict1) | Overwrites with dict2 | All versions |
| ` | ` Operator | Yes | No | Overwrites with dict2 |
| Dictionary Comprehension | Yes | No | Overwrites with dict2 | All versions |
ChainMap | No (creates view) | No | Prioritizes first dict | All versions |
| For Loop | Yes | No | Overwrites with dict2 | All versions |