What is the best single-expression method to merge two dictionaries in Python? | A1Lab@MZeeshanM to PythonEnglish • 7 days ago

What is the best single-expression method to merge two dictionaries in Python?

message-square
0

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 mutate defaults directly instead of creating a new dictionary, use the augmented assignment operator defaults |= overrides (equivalent to defaults.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.