fluttersmith/py-snippetsGitHub ↗

Transform every value in a dict

Build a new dict with a function applied to each value, keeping the keys.

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

Pull one field out of every record, or format every price: keep the keys, change the values.

map_values.py✓ ruff · mypy --strict
from collections.abc import Callable, Mapping
from typing import TypeVar

K = TypeVar("K")
V = TypeVar("V")
R = TypeVar("R")


def map_values(d: Mapping[K, V], fn: Callable[[V], R]) -> dict[K, R]:
    """Return a new dict with ``fn`` applied to every value of ``d``."""
    return {key: fn(value) for key, value in d.items()}
  1. keys and their order are untouched
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> users = {"fred": {"age": 40, "pets": 1}, "pebbles": {"age": 1, "pets": 0}}passed on Python 3.11 to 3.14: >>> map_values(users, lambda user: user["age"]){'fred': 40, 'pebbles': 1}passed on Python 3.11 to 3.14: >>> map_values({"a": "x"}, str.upper){'a': 'X'}
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 applies fn to each value.
  • Keys and their order don’t change, and the input isn’t modified.

Complexity: O(n) time, O(n) space

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

Adapted from map-values in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten as a dict comprehension; typed. Suggest an edit.