Sorting Lists of Tuples and Dictionaries Using key= in Python

⚡ Direct Answer & Key Takeaway

In Python, `sorted(iterable, key=...)` and `list.sort(key=...)` pass each element through the `key` function once to compute a comparison proxy without modifying the original items. To sort tuples by a specific field, pass `key=lambda x: x[1]`; to sort dictionaries by a field, pass `key=lambda d: d['marks']`. Returning a tuple like `(-d['marks'], d['name'])` enables multi-criteria sorting. Both methods use Timsort, guaranteeing stable ordering when keys tie.

1. How Python Evaluates the key= Function During Timsort

By default, sorting a list of tuples compares index `0` first and uses later indices only as tiebreakers, while sorting a list of dictionaries raises a `TypeError` because Python cannot compare two `dict` objects with `<`. Supplying a `key=` callable solves both problems cleanly using a decorate-sort-undecorate pattern. Before reordering, Timsort calls your `key` function exactly once per element—an O(n) step—and stores the computed sort keys alongside the original objects. Comparisons then run on those derived keys rather than the raw tuples or dictionaries. Crucially, the original elements inside the sorted list remain completely intact; the `lambda` only tells Python what value represents each item during ordering. Choose `list.sort()` when in-place mutation is desired and memory matters, or `sorted()` when you need a fresh list while preserving the original input sequence.

  • `list.sort()` mutates the list in place and returns `None`; never assign `x = x.sort()`.
  • `sorted(seq, key=...)` works on any iterable (tuples, sets, dicts) and always returns a new `list`.
  • Sorting dictionaries directly without `key=` triggers `TypeError: '<' not supported between instances of 'dict' and 'dict'`.

2. Single-Field and Multi-Criteria Tuple Keys

Anonymous `lambda` functions shine when extracting a single index or dictionary key inline without cluttering your script with one-off `def` helpers. For a list of `(item_name, price, stock)` tuples, `key=lambda item: item[1]` orders records strictly by `price`. When you need secondary tiebreakers—for instance, ranking records by highest score first and alphabetically by code when scores match—return a tuple from the `lambda`: `key=lambda r: (-r['score'], r['code'])`. Negating numeric values reverses only that numeric field while keeping string tiebreakers ascending, something `reverse=True` alone cannot achieve because `reverse=True` flips every criterion simultaneously. You can also normalize inconsistent casing during comparison using `key=lambda s: s[0].lower()`, ensuring `'apple'` and `'Banana'` sort naturally without altering the stored strings inside the resulting list.

  • Return `(-num, text)` in `lambda` to sort numbers descending and strings ascending together.
  • Use `d.get('field', 0)` inside `lambda` when optional dictionary keys might be missing.
  • Case-insensitive text sorting works via `.lower()` inside `key=` without mutating data.

3. Sort Stability and operator.itemgetter Alternatives

Python's Timsort algorithm is guaranteed to be stable, meaning two elements whose `key` functions produce equal values preserve their original relative order from before the sort. Stability enables a clean multi-pass alternative when descending text sorting is required alongside ascending numbers: first sort by the secondary key, then sort stably by the primary key. In addition, the standard library's `operator.itemgetter` provides a faster C-level replacement for simple index or dictionary-key lambdas, such as `key=itemgetter(1)` for tuples or `key=itemgetter('price')` for dictionaries. While `lambda` remains preferred in CBSE Class 11 and 12 practical files for readability and flexibility with arithmetic expressions like `x[1] * x[2]`, understanding both `itemgetter` and Timsort stability helps you debug subtle tie-breaking behavior in file-handling and SQL-like record processing tasks.

  • Timsort preserves input order whenever two items yield equal sort keys.
  • Two-pass stable sorting handles mixed ascending/descending string fields cleanly.
  • `operator.itemgetter` avoids Python function-call overhead for large record lists.

4. Single-Key Tuple Sort and Multi-Criteria Dict Sort

products = [
    ("Keyboard", 1200, 15),
    ("Mouse", 650, 40),
    ("Monitor", 12500, 8),
    ("USB Hub", 650, 22),
]

by_price = sorted(products, key=lambda item: item[1])
print("Tuples by price:", by_price)

inventory = [
    {"code": "P102", "category": "Audio", "score": 88},
    {"code": "P101", "category": "Input", "score": 95},
    {"code": "P104", "category": "Display", "score": 88},
    {"code": "P103", "category": "Cables", "score": 76},
]

ranked = sorted(inventory, key=lambda r: (-r["score"], r["code"]))
print("Dicts ranked:", [(d["code"], d["score"]) for d in ranked])

Verified Console / Dry-Run Output:

Tuples by price: [('Mouse', 650, 40), ('USB Hub', 650, 22), ('Keyboard', 1200, 15), ('Monitor', 12500, 8)]
Dicts ranked: [('P101', 95), ('P102', 88), ('P104', 88), ('P103', 76)]

5. Common key= Patterns for Tuples and Dictionaries

Data StructureGoalkey= ExpressionTiebreaker Behavior
List of tuplesSort by 2nd element ascendingkey=lambda t: t[1]Preserves input order (stable)
List of tuplesSort by computed total (qty * price)key=lambda t: t[1] * t[2]Preserves input order (stable)
List of dictsHighest score first, then code A-Zkey=lambda d: (-d['score'], d['code'])Breaks score ties using code
List of dictsCase-insensitive name sortkey=lambda d: d['name'].lower()Preserves order when lowercase matches
🎯 1-on-1 Live Mentorship & Free Study Kit

Build Real Python Sorting Confidence

Work through tuple, dictionary, and file-record sorting exercises live with mentors at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 trial class.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing `nums = nums.sort(key=...)`, which assigns `None` to `nums` because `.sort()` works in place.
  • Avoid Mistake: Calling `sorted(dict_list)` without `key=`, raising `TypeError` on dictionary comparisons.
  • Avoid Mistake: Passing `reverse=True` when only the numeric score should be descending and the text tiebreaker should stay ascending.
  • Examiner / Mentor Tip: Remember that `sorted()` always returns a `list`, even if you pass a tuple of records.
  • Examiner / Mentor Tip: Never negate a string inside a `lambda` key (e.g., `-d['name']` raises `TypeError`); use two-pass sorting instead.
  • Examiner / Mentor Tip: When fields tie on `key=`, check the original list positions because Python's Timsort preserves their relative order.

7. Interactive Concept Check Quiz

Question: What is the output of sorted([('B', 2), ('A', 2), ('C', 1)], key=lambda x: x[1])?

8. Frequently Asked Questions

Can I sort a dictionary itself by its values using sorted()?
Yes. `sorted(d.items(), key=lambda kv: kv[1])` returns a list of `(key, value)` tuples ordered by value, which you can wrap in `dict()`.
What happens if a key is missing in one dictionary inside the list?
Using `d['marks']` raises `KeyError`. Replace it with `d.get('marks', 0)` to supply a safe fallback comparison value.
Is a lambda expression allowed to call another function inside key=?
Yes, or you can pass the helper function name directly without parentheses, such as `sorted(items, key=helper_fn)`.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class