brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's operator.itemgetter sorts a list of dicts on two keys

Python
~/tips/tip-python-operator-itemgetter-sort

from operator import itemgetter

Sort rows on one or more fields without writing a lambda.

Sorting a list of dicts by a field usually ends up as key=lambda r: r["size"]. operator.itemgetter says the same thing, I find it easier to read, and can take several fields at once.

from operator import itemgetter

rows = [
    {"name": "b.log", "size": 2},
    {"name": "a.log", "size": 2},
    {"name": "c.log", "size": 1},
]
for r in sorted(rows, key=itemgetter("size", "name")):
    print(r["size"], r["name"])
# 1 c.log
# 2 a.log
# 2 b.log

With two keys it builds a tuple per row, so rows are sorted on size first and on name when sizes are equal. That gives you a stable, predictable order, which is nice when the output ends up in a diff or a report.

It works on anything you can index: dicts, tuples from csv.reader, database rows. For objects there’s attrgetter("size"), which reads attributes instead.

The limit shows up when you want mixed directions, like biggest size first but names A to Z. reverse=True flips the whole tuple, both keys. For numbers you can negate one in a lambda: key=lambda r: (-r["size"], r["name"]). For strings, sort twice instead: first on the secondary key, then on the primary one with reverse=True. Python’s sort is stable, so the first order survives inside equal groups.

Further reading: operator.itemgetter, Sorting HOWTO

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link