Python Program to Merge Two Dictionaries
merged = {**dict1, **dict2} or merged = dict1 | dict2 (Python 3.9+).Examples
How to Think About It
Algorithm
Code
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Method 1: Using dictionary unpacking
merged = {**dict1, **dict2}
print(merged)
# Method 2: Using | operator (Python 3.9+)
merged2 = dict1 | dict2
print(merged2)Dry Run
Let's trace merging dict1 = {'a': 1, 'b': 2} and dict2 = {'b': 3, 'c': 4} using unpacking.
Start with dict1
{'a': 1, 'b': 2}
Unpack dict1 into new dictionary
New dict = {'a': 1, 'b': 2}
Unpack dict2 into new dictionary, overwriting duplicates
New dict = {'a': 1, 'b': 3, 'c': 4}
Return merged dictionary
{'a': 1, 'b': 3, 'c': 4}
| Step | Dictionary Content |
|---|---|
| 1 | {'a': 1, 'b': 2} |
| 2 | {'a': 1, 'b': 2} |
| 3 | {'a': 1, 'b': 3, 'c': 4} |
| 4 | {'a': 1, 'b': 3, 'c': 4} |
Why This Works
Step 1: Unpacking dictionaries
Using {**dict1, **dict2} unpacks all key-value pairs from both dictionaries into a new one.
Step 2: Handling duplicate keys
If a key appears in both, the value from the second dictionary overwrites the first, ensuring the latest value is kept.
Step 3: Using | operator
The | operator (Python 3.9+) merges dictionaries similarly, making the code cleaner and easier to read.
Alternative Approaches
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1.copy()
for k, v in dict2.items():
merged[k] = v
print(merged)Complexity: O(n + m) time, O(n + m) space
Time Complexity
Merging requires visiting all keys in both dictionaries, so time grows with the total number of keys (n and m).
Space Complexity
A new dictionary is created holding all keys and values, so space grows with the total size of both dictionaries.
Which Approach is Fastest?
Using {**dict1, **dict2} or | operator is fastest and most readable; update() is slightly slower due to copying.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Dictionary unpacking {**d1, **d2} | O(n + m) | O(n + m) | Simple, readable merging |
| | operator (Python 3.9+) | O(n + m) | O(n + m) | Clean syntax, modern Python |
| dict.update() with copy | O(n + m) | O(n + m) | When modifying a copy explicitly |
| Manual loop | O(n + m) | O(n + m) | Learning or custom merge logic |
{**dict1, **dict2} for a quick and readable merge in Python versions before 3.9.+ operator, which is not supported and causes errors.