Legends ofPythos
Claim your name
Working with Data

Sorting the way you want

Lesson 10 of 14

Watch the lesson1:23 · with Torsten
You already know how to sort a list of numbers or strings. But what if your data is more complex? What if each item has several fields, and you only care about one of them?

The key argument

Both sorted() and the .sort() method accept a keyword called key. The value you pass to key is a function. Python calls that function once for every item in your list, uses the result as a temporary "label", sorts by those labels, but returns or keeps the original items.
words = ['banana', 'kiwi', 'fig']
by_length = sorted(words, key=len)
print(by_length)
Sorting words by length without changing them

Lambdas: tiny one-line functions

When the key function is simple, writing a full def feels heavy. A lambda lets you define an anonymous inline function in one expression:
last_char = lambda s: s[-1]
print(last_char('hello'))
A lambda that returns the last character of its argument
So sorted(words, key=lambda w: len(w)) is exactly the same as using a named function that returns len(w). You will see this pattern everywhere.

Sorting lists of dictionaries

players = [
    {'name': 'Ada',  'score': 42},
    {'name': 'Linus','score': 91},
    {'name': 'Grace','score': 67}
]
top_players = sorted(players, key=lambda p: p['score'], reverse=True)
for p in top_players:
    print(p)
Sort players by their score, highest first
reverse=True flips the order. Without it you get ascending (smallest first). With it you get descending (largest first).

Sorting by two fields at once

What if scores tie? You can return a tuple from your key function. Python compares tuples element-by-element, so the first value is primary and the second breaks ties.
players = [
    {'name': 'Ada',  'score': 90},
    {'name': 'Zoe',  'score': 75},
    {'name': 'Ben',  'score': 90}
]
sorted_players = sorted(players, key=lambda p: (-p['score'], p['name']))
for p in sorted_players:
    print(p)
Sort by score descending, then name ascending on ties

Your turn

0 of 3 solved

Exercise 1

+30 XP
Sort the list of words by length, shortest first. Ties should keep their original relative order (Python's sort is stable). Store the new list in sorted_words; do not modify words.
words = ['pear', 'kiwi', 'fig', 'apple']

Run your code to check it against the tests.

Exercise 2

+30 XP
Sort the list of book dictionaries by their price from highest to lowest. Store the new list in sorted_books; do not modify books.
books = [
    {'title': 'Dune',        'price': 14},
    {'title': 'Neuromancer', 'price': 9},
    {'title': 'Snow Crash',  'price': 22}
]

Run your code to check it against the tests.

Exercise 3

+30 XP
Sort the list of task dictionaries by priority descending, then by due date ascending (earliest first) when priorities tie. Store the new list in sorted_tasks; do not modify tasks.
tasks = [
    {'id': 'A', 'priority': 2, 'due': '2025-11-30'},
    {'id': 'B', 'priority': 1, 'due': '2025-12-01'},
    {'id': 'C', 'priority': 2, 'due': '2025-11-28'}
]

Run your code to check it against the tests.