pysnippets.dicts.sort_dict_by_value
Sort a dictionary by value
sort_dict_by_value(d: Mapping[K, V], *, reverse: bool = False) -> dict[K, V]
Return a copy of a dict ordered by its values, ascending or descending.
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))- 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).
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
d.items()gives(key, value)pairs;itemgetter(1)sorts them by value.dict()rebuilds the mapping in that order.reverseis keyword-only, so a call readsreverse=True, never a bareTrue.
Complexity: O(n log n) time, O(n) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from 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.