pysnippets.dicts.key_of_max
Key of the largest or smallest value
key_of_max(d: Mapping[K, V]) -> KReturn the key of the largest value ind; on a tie, the first one.key_of_min(d: Mapping[K, V]) -> KReturn the key of the smallest value ind; on a tie, the first one.
Find the key with the largest or smallest value using max() or min() with a key function.
Which product sold most? max(d.values()) gives the number but not the product. Rank the keys by value instead.
key_of_max.py✓ ruff · mypy --strict
from collections.abc import Mapping
from typing import Any, Protocol, TypeVar
class _SupportsLessThan(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
K = TypeVar("K")
V = TypeVar("V", bound=_SupportsLessThan)
def key_of_max(d: Mapping[K, V]) -> K:
"""Return the key of the largest value in ``d``; on a tie, the first one."""
return max(d, key=d.__getitem__)
def key_of_min(d: Mapping[K, V]) -> K:
"""Return the key of the smallest value in ``d``; on a tie, the first one."""
return min(d, key=d.__getitem__)- iterating a dict yields keys; key= ranks them by value
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> key_of_max({"a": 4, "b": 0, "c": 13})'c'passed on Python 3.11 to 3.14: >>> key_of_max({"x": 1, "y": 1})'x'passed on Python 3.11 to 3.14: >>> key_of_min({"a": 4, "b": 0, "c": 13})'b'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
- Iterating a dict yields its keys.
key=d.__getitem__ranks each key by its value.- On a tie,
maxandminreturn the first key, in dict order. An empty dict raisesValueError.
Complexity: O(n) time, O(1) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.dicts.key_of_max import key_of_max, key_of_minNo dependencies: copy key_of_max.py into your project, or clone the repo.Adapted from key-of-max and key-of-min in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Merged max and min into one page; typed. Suggest an edit.