fluttersmith/py-snippetsGitHub ↗

Key of the largest or smallest value

Find the key with the largest or smallest value using max() or min() with a key function.

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

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

How it works

  • Iterating a dict yields its keys.
  • key=d.__getitem__ ranks each key by its value.
  • On a tie, max and min return the first key, in dict order. An empty dict raises ValueError.

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

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