Meaning
Creates a new dictionary that merges dict1 and dict2, with values from dict2 overriding those in dict1 for duplicate keys. This avoids mutating the original dictionaries, which is useful when you need to preserve immutable configuration or API payloads. Use it when combining defaults with overrides or merging multiple sources into a fresh dict.
Primary Function
Merge two dictionaries into a new dictionary, giving precedence to the right-hand operand.
Communicative Purpose
Express dictionary merging concisely, emphasizing immutability and precedence of the right operand.
Pattern
dict1 | dict2
Core Structure
... | ...
Função primária
Merge two dictionaries into a new dictionary, giving precedence to the right-hand operand.
Propósito comunicativo
Express dictionary merging concisely, emphasizing immutability and precedence of the right operand.
Situações de gatilho
Configuration: combining default settings with user-provided overrides API: merging successive response payloads into a unified dict Data aggregation: building a summary dictionary from multiple sources without altering originals
Contextos
Configuration merging, data aggregation, API response composition, default parameter overrides.
Padrão
dict1 | dict2
Estrutura central
... | ...
Slots de substituição
dict1: any mapping (typically dict); dict2: any mapping (typically dict)
Colocados típicos
- dict
- config
- defaults
- overrides
- merge
- update
- unpacking
Substituições comuns
- dict1.update(dict2) (in‑place)
- {**dict1
- **dict2} (unpacking)
- {**dict2
- **dict1} (reverse precedence)
- collections.ChainMap
Erros comuns
Assuming the operator modifies dict1 in‑place (it returns a new dict); confusing with set union (+) or list concatenation; expecting a recursive/deep merge of nested dicts.
Similar / contraste
dict.update (in‑place), {**a, **b} (dict unpacking), collections.ChainMap (view), itertools.chain (for items)
Interferências
Coming from Python: may confuse the dict merge operator with set union or list concatenation → remember that | for dicts merges mappings and does not mutate the originals.
Família do chunk
- dict-merge-operators
Nuance
Do not use this operator when a deep merge of nested dictionaries is required, as it only replaces top-level keys. Performance is O(n) in the total number of keys, creating a shallow copy of the merged dict. Note that insertion order preserves left-to-right sequence, with later keys overwriting earlier ones, but nested dicts are replaced rather than merged.
Efeito pragmático
Signals intent to create an immutable merged configuration, favoring a functional style over side‑effects.
Dica de memória
Think of the Unix pipe: dict1 | dict2 pipes the second dict’s values over the first.
Nota
Available from Python 3.9; for earlier versions use {**dict1, **dict2} or dict1.copy(); dict1.update(dict2).
Upgrade path
For Python <3.9 use {**dict1, **dict2} or dict1.copy(); dict1.update(dict2).
Log in to save chunks.