Dict Union Operators Merge Flat Keys
The dict union operator merges flat keys with the right side winning, while nested dicts are replaced wholesale — deep merging still needs recursion.
Code
defaults = {"host": "0.0.0.0", "port": 8080, "debug": False}
overrides = {"port": 9090, "debug": True}
# union:右侧优先的浅合并,重复键整体取右值
merged = defaults | overrides
print("merged:", merged)
# |= 就地合并:适合逐段累积配置
partial = {"port": 9090}
partial |= {"host": "127.0.0.1"}
print("accumulated:", partial)
# 联合不递归:嵌套 dict 作为整值被右侧替换,深层合并要另写递归
base = {"db": {"host": "a", "port": 5432}}
patch = {"db": {"host": "b"}}
print("nested replaced:", base | patch)Output
Captured from a sandboxed run of this snippet in the build pipeline.
merged: {'host': '0.0.0.0', 'port': 9090, 'debug': True}
accumulated: {'port': 9090, 'host': '127.0.0.1'}
nested replaced: {'db': {'host': 'b'}}How it works
Top-level bindings defaults, overrides, merged, partial hold the demo state — nothing sits inside a function scope.
Putting it to use
The demo output is labeled (merged:, accumulated:, nested replaced:), so every printed line maps back to its originating operation.
Core lines
defaults = {"host": "0.0.0.0", "port": 8080, "debug": False}
base = {"db": {"host": "a", "port": 5432}}
overrides = {"port": 9090, "debug": True}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `defaults`, `overrides`, `merged`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.