Sort records by two fields with operator.itemgetter
Also published in our Blogger archive.
Sort records by two fields with operator.itemgetter
By Batu.
operator.itemgetter("severity", "opened") makes a key function that retrieves two dictionary fields from each ticket. When sorted() calls it, each ticket receives a comparison key such as (1, 4) or (2, 1). Tuple comparison orders by severity first and uses opened only to break a severity tie. The example therefore places the two severity-1 tickets before the severity-2 ticket, with R-2 before R-3 because its opening sequence is smaller.
sorted() returns a new list; it does not rearrange the original tickets list. The assertion verifies the identifier order while the printed comma-separated IDs make the exact result visible. This is useful when the stored records have several fields but the ordering rule should remain compact and explicit.
The field names are not optional: itemgetter applied to a dictionary uses subscription, so a ticket missing severity or opened raises KeyError. Values also need to be mutually orderable for the keys that are compared; mixing an integer severity with an unrelated non-orderable type can raise TypeError. If two complete keys are equal, Python's stable sort preserves their prior input order, but that is not a substitute for adding a real third ordering field when a deterministic external order is required.
See the Python operator.itemgetter() documentation.
This Batu Lab Notes draft received AI assistance.
from operator import itemgetter
tickets = [
{"id": "R-3", "severity": 2, "opened": 1},
{"id": "R-1", "severity": 1, "opened": 4},
{"id": "R-2", "severity": 1, "opened": 2},
]
ordered = sorted(tickets, key=itemgetter("severity", "opened"))
identifiers = [ticket["id"] for ticket in ordered]
assert identifiers == ["R-2", "R-1", "R-3"]
assert tickets[0]["id"] == "R-3"
print(",".join(identifiers))
Expected stdout:
R-2,R-1,R-3