Algorithmssorting nested collections

Sorting Rows, Tuples, and Nested Structures

TT
Testlaa Team
May 14, 20261 min read

You often sort lists of tuples, rows of CSV, or JSON objects—not plain integers. Python’s key= and operator.itemgetter let you project nested fields without reshaping data permanently.

Why this shows up in the real world

Airline manifests sort passengers by (zone, seat_row, seat_letter) for boarding. Leaderboards sort (score desc, time asc) to break ties fairly. Data pipelines sort (partition_date, user_id) before compaction. Nested sorts encode business policy directly in keys.

Core idea (explained for students)

Prefer key=lambda row: (row["score"], row["name"]) over mutating rows. For descending on one field while ascending on another, combine negation and tuples carefully. When sorting mixed types is impossible, normalize first (parse dates to datetime).

Try this in Python

rows = [{"city": "Chennai", "temp": 32}, {"city": "Ooty", "temp": 18}]
print(sorted(rows, key=lambda r: (-r["temp"], r["city"])))

Common mistakes

  • Sorting strings that look like numbers—lexicographic '10' < '2'.
  • Time zones naive vs aware mixing.
  • Key function raising exceptions on some rows—validate data first.

Key takeaways

  • Use tuples for multi-key sorts.
  • Normalize types before sorting.
  • Prefer stable sorts to preserve hidden tie columns.

Tags:

SortingPythonStudents