pysnippets.dicts.pluck
Pluck one field from a list of dicts
pluck(records: Iterable[Mapping[K, V]], key: K) -> list[V | None]
Collect the value of a key from each dict, with None where it's missing.
Turn a list of records into a list of one field, such as every user’s age.
pluck.py✓ ruff · mypy --strict
from collections.abc import Iterable, Mapping
from typing import TypeVar
K = TypeVar("K")
V = TypeVar("V")
def pluck(records: Iterable[Mapping[K, V]], key: K) -> list[V | None]:
"""Return ``record[key]`` for each record, or ``None`` where it's missing."""
return [record.get(key) for record in records]- .get keeps one result per record, even when the key is missing
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> simpsons = [{"name": "lisa", "age": 8}, {"name": "homer", "age": 36}, {}]passed on Python 3.11 to 3.14: >>> pluck(simpsons, "age")[8, 36, None]passed on Python 3.11 to 3.14: >>> pluck([], "age")[]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
.get(key)returnsNonefor a missing key instead of raising.- The result always has one entry per record, so it lines up with the input.
- For a required field,
[r[key] for r in records]fails loudly instead.
Complexity: O(n) time, O(n) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.dicts.pluck import pluckNo dependencies: copy pluck.py into your project, or clone the repo.Adapted from pluck in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed; added the missing-key example. Suggest an edit.