fluttersmith/py-snippetsGitHub ↗

Find the keys for a value

Return every key whose value equals a given value.

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

Dicts are fast from key to value only. Going the other way means a scan, so make it a readable one.

find_keys.py✓ ruff · mypy --strict
from collections.abc import Mapping
from typing import TypeVar

K = TypeVar("K")


def find_keys(d: Mapping[K, object], value: object) -> list[K]:
    """Return every key of ``d`` whose value equals ``value``."""
    return [key for key, v in d.items() if v == value]
  1. a linear scan: dicts index by key, not by value
examples✓ 2 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> find_keys({"Peter": 10, "Isabel": 11, "Anna": 10}, 10)['Peter', 'Anna']passed on Python 3.11 to 3.14: >>> find_keys({"Peter": 10}, 99)[]
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 comprehension over d.items() keeps the matching keys, in dict order.
  • No match gives an empty list, not an error.
  • If you do this lookup often, build an inverted dict once with collect_dictionary.

Complexity: O(n) time, O(k) space for k matches

Importfrom pysnippets.dicts.find_keys import find_keysNo dependencies: copy find_keys.py into your project, or clone the repo.

Adapted from find-keys in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed; no longer shadows the dict builtin. Suggest an edit.