Use the dictionary merge operator | (merged = dict1 | dict2), introduced in Python 3.9 (PEP 584), to combine two dictionaries into a new dictionary in a single clean expression without mutating either original dictionary.
Basic Example
# 1. Define two dictionaries (note the overlapping key 'b')
defaults = {"a": 1, "b": 2}
overrides = {"b": 99, "c": 3}
# 2. Merge into a new dictionary (right-hand dictionary wins on key collisions)
merged = defaults | overrides
print(merged) # Output: {'a': 1, 'b': 99, 'c': 3}
print(defaults) # Output: {'a': 1, 'b': 2} (unchanged)
Key Details & Alternative Expressions
- Conflict resolution rule (right wins): When both dictionaries share a key, the value from the dictionary on the right (
overrides) overwrites the value from the left (defaults). - In-place merge operator (
|=): If you want to mutatedefaultsdirectly instead of creating a new dictionary, use the augmented assignment operatordefaults |= overrides(equivalent todefaults.update(overrides)). - Dictionary unpacking (
{**d1, **d2}): For older codebases running Python 3.5–3.8, dictionary unpacking is the standard single-expression alternative and behaves identically to|:merged = {**defaults, **overrides} - Chaining three or more dictionaries: Both operators scale cleanly to multiple dictionaries in a single expression:
final_config = base_config | env_config | cli_args - Shallow copy behavior: Both
|and{**d1, **d2}perform a shallow merge—nested mutable objects (such as lists or inner dictionaries) are copied by reference rather than recursively merged.
Comparison of Single-Expression Merge Methods
| Method | Minimum Python Version | Creates New Dict? | Supports Non-Dict Mappings? | Best Used When |
|---|---|---|---|---|
d1 | d2 |
Python 3.9+ | Yes | Yes (any Mapping with dict) |
Modern Python 3.9+ codebases (cleanest & most readable). |
{**d1, **d2} |
Python 3.5+ | Yes | Yes (keys must be strings in older versions) | Supporting Python 3.5–3.8 or mixing literal keys ({**d1, "k": 1}). |
d1 |= d2 |
Python 3.9+ | No (mutates d1) |
Yes (accepts any iterable of key-value pairs) | Updating an existing dictionary in place. |
dict(d1, **d2) |
Python 2.7+ | Yes | No (d2 keys must be valid string identifiers) |
Avoid in modern code—fails if d2 has integer or tuple keys. |
You must log in or register to comment.
