pysnippets.dicts.invert_dictionary
Invert a dictionary
invert_dictionary(d: Mapping[K, V]) -> dict[V, K]
Swap keys and values with a dict comprehension; the last key wins on shared values.
Turn a code-to-name table into a name-to-code table.
invert_dictionary.py✓ ruff · mypy --strict
from collections.abc import Hashable, Mapping
from typing import TypeVar
K = TypeVar("K")
V = TypeVar("V", bound=Hashable)
def invert_dictionary(d: Mapping[K, V]) -> dict[V, K]:
"""Swap the keys and values of ``d``."""
return {value: key for key, value in d.items()}- values become keys, so they must be hashable
examples✓ 2 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> invert_dictionary({"Peter": 10, "Isabel": 11, "Anna": 9}){10: 'Peter', 11: 'Isabel', 9: 'Anna'}passed on Python 3.11 to 3.14: >>> invert_dictionary({"a": 1, "b": 1}){1: 'b'}Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
- A dict comprehension builds the new dict in one pass.
- Values become keys, so they must be hashable.
- Two keys with the same value collide, and the later one wins. If that loses data you need, use
collect_dictionary.
Complexity: O(n) time, O(n) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.dicts.invert_dictionary import invert_dictionaryNo dependencies: copy invert_dictionary.py into your project, or clone the repo.Adapted from invert-dictionary in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed; documents and tests the collision rule. Suggest an edit.