Most of the small scripts I write end the same way: I have a list of records, and I need to show them in an order that makes sense to a person. Busiest first. Oldest first. Grouped by area, then by time. Python makes sorting look easy, and it is, but there are a few details that decide whether your report is right or just looks right. Here is how I handle them now.
sorted versus .sort
There are two tools, and they behave differently.
counts = [42, 7, 19, 88]
ranked = sorted(counts) # returns a new list
counts.sort() # changes the list in place, returns None
I use sorted almost everywhere. It leaves the original data alone, which matters when the same list feeds more than one report. The classic bug with .sort is writing counts = counts.sort() and ending up with None. If you want a sorted copy, ask for one.
Sorting records with key
Real data is rarely a list of numbers. It is usually a list of dictionaries, one per row.
stops = [
{"area": "New Haven", "stop": "Elm St", "window": "10:30"},
{"area": "Bridgeport", "stop": "Main St", "window": "09:15"},
{"area": "New Haven", "stop": "Chapel St", "window": "08:45"},
]
by_window = sorted(stops, key=lambda row: row["window"])
The key argument is a function that Python calls once per item. Whatever it returns is what gets compared. The rows themselves are never compared directly, which is good, because Python cannot compare two dictionaries anyway.
Notice the times are stored as "08:45" with a leading zero. String sorting compares character by character, so "9:15" would land after "10:30". When I sort times or IDs stored as text, I either make sure they are zero padded or convert them first.
itemgetter: the same thing, cleaner
The operator module has a helper that replaces most of those lambdas.
from operator import itemgetter
by_window = sorted(stops, key=itemgetter("window"))
It reads like what it does, and it is a little faster on large lists. For objects instead of dictionaries, attrgetter does the same job with attribute names.
Sorting by more than one field
This is where itemgetter really earns its place. Give it several keys and it returns a tuple, and tuples compare field by field.
by_area_then_window = sorted(stops, key=itemgetter("area", "window"))
for row in by_area_then_window:
print(row["area"], row["window"], row["stop"])
Output:
Bridgeport 09:15 Main St
New Haven 08:45 Chapel St
New Haven 10:30 Elm St
Area first, and inside each area, earliest window first. In dispatch work this was exactly how a route sheet needed to read, and it is one line of Python.
Mixed directions: descending one field, ascending another
Sometimes I want the busiest area first but times inside it in normal order. reverse=True flips everything, so it cannot do that alone. The trick is that Python's sort is stable: items that compare equal keep the order they already had. So you sort twice, starting with the least important field.
jobs = [
{"line": "A", "units": 120, "start": "07:00"},
{"line": "B", "units": 340, "start": "06:30"},
{"line": "C", "units": 120, "start": "06:00"},
]
step1 = sorted(jobs, key=itemgetter("start"))
result = sorted(step1, key=itemgetter("units"), reverse=True)
Now the highest unit count comes first, and when two lines tie on units, the earlier start time wins. I used to try to cram this into one clever key function. Two plain sorts are easier to read and easier to check.
Case and missing values
Two things break sorts in real exports.
Text with mixed capitalization sorts uppercase before lowercase, so "Zeta" lands before "alpha". A key of str.casefold fixes that:
names = ["delta", "Alpha", "charlie", "Bravo"]
print(sorted(names, key=str.casefold))
Missing values are worse. If one row has None where the others have numbers, Python raises a TypeError, because it cannot compare None with an int. I handle it in the key by returning a tuple that pushes blanks to the end:
rows = [{"qty": 5}, {"qty": None}, {"qty": 2}]
def qty_key(row):
value = row["qty"]
return (value is None, value or 0)
print(sorted(rows, key=qty_key))
False sorts before True, so every row with a real number comes first, in order, and the blanks collect at the bottom where someone can see them and fix the source.
Top N without sorting everything
When I only need the top few, heapq is a good fit:
import heapq
top_three = heapq.nlargest(3, jobs, key=itemgetter("units"))
On a short list it makes no real difference. On a big export it skips sorting rows you will never show.
What I keep in mind
Sorting is the last step before a person reads the data, so mistakes there are the ones people notice. When I ran production and route operations, a list in the wrong order cost time on the floor, even when every number on it was correct. My checklist is short: use sorted so the source stays untouched, use itemgetter for clarity, sort in two passes when directions differ, and decide on purpose where blanks and odd capitalization should go.
If your reports are built from a pile of lambdas, try replacing one with itemgetter and see how much easier it is to read next week.
Originally published at tonycantave.com by Tony Sterlin Cantave, a Connecticut software developer.
Top comments (0)