fluttersmith/py-snippetsGitHub ↗

Pluck one field from a list of dicts

Collect the value of a key from each dict, with None where it's missing.

Dicts#mapping#nestedO(n) time✓ 3 examples pass on 3.11–3.14

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]
  1. .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).

How it works

  • .get(key) returns None for 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

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