fluttersmith/py-snippetsGitHub ↗

Sort a dictionary by value

Return a copy of a dict ordered by its values, ascending or descending.

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

Dicts keep insertion order, so a sorted dict is a dict built from sorted items.

sort_dict_by_value.py✓ ruff · mypy --strict
from collections.abc import Mapping
from operator import itemgetter
from typing import Any, Protocol, TypeVar


class _SupportsLessThan(Protocol):
    def __lt__(self, other: Any, /) -> bool: ...


K = TypeVar("K")
V = TypeVar("V", bound=_SupportsLessThan)


def sort_dict_by_value(d: Mapping[K, V], *, reverse: bool = False) -> dict[K, V]:
    """Return a copy of ``d`` ordered by value."""
    return dict(sorted(d.items(), key=itemgetter(1), reverse=reverse))
  1. itemgetter(1) picks the value from each (key, value) pair
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> d = {"one": 1, "three": 3, "five": 5, "two": 2, "four": 4}passed on Python 3.11 to 3.14: >>> sort_dict_by_value(d){'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}passed on Python 3.11 to 3.14: >>> sort_dict_by_value(d, reverse=True){'five': 5, 'four': 4, 'three': 3, 'two': 2, 'one': 1}
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

  • d.items() gives (key, value) pairs; itemgetter(1) sorts them by value.
  • dict() rebuilds the mapping in that order.
  • reverse is keyword-only, so a call reads reverse=True, never a bare True.

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

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

Adapted from sort-dict-by-value in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: itemgetter instead of a lambda; keyword-only reverse; typed. Suggest an edit.