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