fluttersmith/py-snippetsGitHub ↗

Invert a dictionary

Swap keys and values with a dict comprehension; the last key wins on shared values.

Dicts#mappingO(n) time✓ 2 examples pass on 3.11–3.14

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()}
  1. 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).

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

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