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.

PythonConfig Management

Code

pythonsnippet
16 lines
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

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`.