Invert A Dict For O(1) Reverse Lookups
Swapping keys and values with a dict comprehension gives O(1) reverse lookups; duplicate values need setdefault grouping or the inversion loses rows.
Code
def invert(mapping: dict) -> dict:
# 字典推导式交换键值:值必须可哈希,重复值时后者覆盖前者
return {code: name for name, code in mapping.items()}
status_names = {200: "ok", 404: "not_found", 500: "server_error"}
status_codes = invert(status_names)
print(status_codes)
# 反查走新字典:O(1) 命中,不用每次扫描 values()
print(status_codes["not_found"], status_codes.get("gone", -1))
# 值重复时直接反转有损:用 setdefault 反转成一对多的分组
roles = {"alice": "admin", "bob": "admin"}
by_role = {}
for user, role in roles.items():
by_role.setdefault(role, []).append(user)
print(by_role)Output
Captured from a sandboxed run of this snippet in the build pipeline.
{'ok': 200, 'not_found': 404, 'server_error': 500}
404 -1
{'admin': ['alice', 'bob']}Inside the snippet
Invert A Dict For O(1) Reverse Lookups is built around the function invert.
Repetition is confined to for user, role in roles.items() — the rest of the file is straight-line.
It builds and returns a fresh value rather than reusing its inputs.
Putting it to use
The main signature reads def invert(mapping: dict) -> dict
invert is the public entry point; everything else in the file exists to support it.
Core lines
return {code: name for name, code in mapping.items()}
Interactive Tools for This Topic
FAQ
- Does `invert` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `invert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.