Skip to content
Python Basics: Sorting Records with operator

Python Basics: Sorting Records with operator

October 12, 2026

Sorting records often starts with choosing a field. Python’s operator module provides small helper functions that extract dictionary items or object attributes for sorted() to compare.

Use Python 3.12 or newer on Linux. Each example runs independently and only prints sample data.

Sort dictionaries by a field

Save as demo_operator_1.py:

from operator import itemgetter

jobs = [
    {"name": "backup", "minutes": 12},
    {"name": "sync", "minutes": 3},
    {"name": "report", "minutes": 8},
]
ordered_jobs = sorted(jobs, key=itemgetter("minutes"))
print([job["name"] for job in ordered_jobs])
print([job["name"] for job in jobs])

Run it:

python3 demo_operator_1.py

Output:

['sync', 'report', 'backup']
['backup', 'sync', 'report']

itemgetter("minutes") creates a function that reads the minutes item from each record. It does the same job as lambda job: job["minutes"] here. sorted() returns a new list and leaves the input order unchanged; the dictionaries themselves are still shared.

Every record must contain the selected key. A missing key raises KeyError, and incompatible values, such as a mix of integers and strings, cannot be sorted together this way.

Break ties with another field

Save as demo_operator_2.py:

from operator import itemgetter

jobs = [
    {"name": "sync", "priority": 2},
    {"name": "report", "priority": 1},
    {"name": "backup", "priority": 1},
]
ordered_jobs = sorted(jobs, key=itemgetter("priority", "name"))
print([job["name"] for job in ordered_jobs])

Run it:

python3 demo_operator_2.py

Output:

['backup', 'report', 'sync']

With two keys, itemgetter() returns a tuple. Python compares the priority first, then the name when priorities match. Both fields sort in ascending order. Adding reverse=True reverses the whole ordering, including the tie-breaker. Records whose complete keys match keep their original relative order because Python’s sort is stable.

Sort objects by an attribute

Save as demo_operator_3.py:

from operator import attrgetter
from types import SimpleNamespace

jobs = [
    SimpleNamespace(name="backup", minutes=12),
    SimpleNamespace(name="sync", minutes=3),
]
ordered_jobs = sorted(jobs, key=attrgetter("minutes"))
print([job.name for job in ordered_jobs])

Run it:

python3 demo_operator_3.py

Output:

['sync', 'backup']

Use attrgetter() for attribute access such as job.minutes; use itemgetter() for indexing such as job["minutes"]. A missing attribute raises AttributeError. For a computed key or a default for missing values, write a small function or lambda instead.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on