Dict Views Compare Keys With Set Algebra
Use dict.keys() and dict.items() views as sets: subtract to find added and removed keys, intersect for changed pairs, and rely on views tracking live mutations.
Code
# keys()/items() 是实时视图,且自带完整集合运算语义
previous = {"timeout": 30, "retries": 3, "endpoint": "/v2/orders"}
current = {"timeout": 45, "retries": 3, "tls": True}
print("added :", sorted(current.keys() - previous.keys()))
print("removed:", sorted(previous.keys() - current.keys()))
print("shared :", sorted(previous.keys() & current.keys()))
print(
"changed:",
sorted(k for k in previous.keys() & current.keys() if previous[k] != current[k]),
)
# items() 视图按 (键, 值) 对做交集:只留下完全一致的行
print("identical rows:", previous.items() & current.items())
# 视图是活的:字典一变,视图立刻跟随,无需重新获取
keys = current.keys()
current["endpoint"] = "/v2/orders"
print("endpoint in same view?", "endpoint" in keys, "| size:", len(keys))Output
Captured from a sandboxed run of this snippet in the build pipeline.
added : ['tls']
removed: ['endpoint']
shared : ['retries', 'timeout']
changed: ['timeout']
identical rows: {('retries', 3)}
endpoint in same view? True | size: 4What the code does
Top-level bindings previous, current, keys hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (removed:, shared :, changed:), so every printed line maps back to its originating operation.
Statements that matter
previous = {"timeout": 30, "retries": 3, "endpoint": "/v2/orders"}
current = {"timeout": 45, "retries": 3, "tls": 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
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `previous`, `current`, `keys`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.