The dictionary union operator creates a new outer mapping, with right-hand values winning duplicate keys.
Python dictionary union: new mapping, shared nested values
Operation contract
The region defaults contain a list of allowed depots. A union overrides only the dispatch window and keeps the original list as a shared value. Appending through the merged mapping changes the defaults. Copying that list before publication isolates it. A merge is a key-level choice, not a full configuration snapshot.
Failure and ownership boundary
A configuration layer must decide whether later mutations are allowed at all. Nested dictionaries and lists need their own copies or an immutable representation. Python configuration precedence: merge, validate, then publish, Python ChainMap: live configuration layers versus an owned snapshot and Python shallow and deep copies: preserve aliases deliberately show alternatives.
Working program
defaults = {"window": 30, "depots": ["DEL"]}
configured = defaults | {"window": 15}
configured["depots"].append("BOM")
owned = configured | {"depots": list(configured["depots"])}
owned["depots"].append("MAA")
print(defaults)
print(configured["window"])
print(owned["depots"])Output
{'window': 30, 'depots': ['DEL', 'BOM']}
15
['DEL', 'BOM', 'MAA']Costs and limits
A union copies O(n+m) outer entries in ordinary mappings; copying the depot list adds O(k) time and storage for k depots. Deep ownership costs depend on the entire nested object graph.
Common Mistakes
- Right-hand precedence does not copy nested values.
- Do not publish a shared mutable configuration as a snapshot.
Connected lessons
Python configuration precedence: merge, validate, then publish, Python ChainMap: live configuration layers versus an owned snapshot, Python shallow and deep copies: preserve aliases deliberately.
