How to Merge Two Dictionaries in Python Quickly and Easily
You can merge two dictionaries in Python using the
{**dict1, **dict2} syntax or the dict1 | dict2 operator (Python 3.9+). Both methods combine keys and values, with later keys overwriting earlier ones if duplicates exist.Syntax
There are two common ways to merge dictionaries in Python:
{**dict1, **dict2}: Unpacks both dictionaries into a new one.dict1 | dict2: Uses the merge operator available in Python 3.9 and later.
In both cases, if the same key exists in both dictionaries, the value from dict2 will overwrite the one from dict1.
python
merged_dict = {**dict1, **dict2}
# or in Python 3.9+
merged_dict = dict1 | dict2Example
This example shows how to merge two dictionaries using both methods and prints the result.
python
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using unpacking
merged1 = {**dict1, **dict2}
print('Merged with unpacking:', merged1)
# Using | operator (Python 3.9+)
merged2 = dict1 | dict2
print('Merged with | operator:', merged2)Output
Merged with unpacking: {'a': 1, 'b': 3, 'c': 4}
Merged with | operator: {'a': 1, 'b': 3, 'c': 4}
Common Pitfalls
Some common mistakes when merging dictionaries include:
- Using
dict1.update(dict2)modifiesdict1in place instead of creating a new dictionary. - Trying to merge with
+operator, which is not supported for dictionaries. - Using the
|operator in Python versions earlier than 3.9 causes errors.
python
dict1 = {'x': 1}
dict2 = {'y': 2}
# Wrong: + operator not supported
# merged = dict1 + dict2 # This will cause a TypeError
# Right: create new dict with unpacking
merged = {**dict1, **dict2}
print(merged)Output
{'x': 1, 'y': 2}
Quick Reference
Summary of dictionary merge methods:
| Method | Description | Python Version | Modifies Original? |
|---|---|---|---|
| {**dict1, **dict2} | Unpack and merge into new dict | All modern versions | No |
| dict1 | dict2 | Merge using operator | 3.9+ | No |
| dict1.update(dict2) | Update dict1 in place | All versions | Yes |
Key Takeaways
Use {**dict1, **dict2} to merge dictionaries without changing originals.
The | operator merges dictionaries cleanly in Python 3.9 and later.
If keys overlap, values from the second dictionary overwrite the first.
Avoid using + operator for dictionaries; it causes errors.
dict1.update(dict2) changes dict1 instead of creating a new dictionary.