pysnippets.dicts.find_keys
Find the keys for a value
find_keys(d: Mapping[K, object], value: object) -> list[K]
Return every key whose value equals a given value.
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]- 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).
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 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
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from 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.