pysnippets.dicts.map_values
Transform every value in a dict
map_values(d: Mapping[K, V], fn: Callable[[V], R]) -> dict[K, R]
Build a new dict with a function applied to each value, keeping the keys.
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()}- 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).
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 dict comprehension applies
fnto each value. - Keys and their order don’t change, and the input isn’t modified.
Complexity: O(n) time, O(n) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from 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.