SypherTec
…
PART 3 · 07 OF 085 MIN READUPDATED 20 NOV 2026

Sorting: Biggest Spends First

Your report lists expenses in the order you typed them. This lesson puts them in order of size, so your three biggest spends get a section of their own.

The concept

Here is your tracker as the last lesson left it. Run it:

WHERE YOU LEFT OFF · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

Your Latest three section follows the order of your receipt lines. Your biggest spends could be anywhere in that list. Now run this:

NUMBERS IN ORDER · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

The first line holds the same five amounts, from smallest to largest. That is sorted(), a built-in function that gives back a new list with the items in order.

The second line adds reverse=True, which flips the order: largest first. The third line is amounts itself, still in the order you typed it. sorted never changes the list you hand it. It builds a new one.

Text sorts too. Run this:

TEXT IN ORDER · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

The words are in alphabetical order, compared letter by letter. But Bus fare and Lunch came before data bundle. To Python, every capital letter comes before every lowercase letter, so Z sorts before a. Text in one case, like your lowercase categories, sorts the way you expect.

Your expenses are records, though, not plain numbers. Run this:

RECORDS IN ORDER OF AMOUNT · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

The records came out smallest amount first, each one whole. The new part is key=amount_of. It hands sorted your amount_of function. sorted calls it once for every record and gets back 2500, 800 and 4200. Then it puts the records in order of those values.

That function is the key: it takes one item and returns the value to sort by. Records need one, because Python cannot guess what makes one record smaller than another. It could be the item, the category or the amount. The key decides.

Look again at key=amount_of. There are no parentheses after the name. This trips up almost everyone, because every call so far has had them. But the functions lesson showed that a name without parentheses names the function, without calling it. Here, that is what you want. You hand the function over, and sorted does the calling, with a record filled in each time.

The syntax

top_three = sorted(expenses, key=amount_of, reverse=True)[:3]
  • sorted(expenses) gives back a new list of the same items, smallest first. expenses keeps its order.
  • key=amount_of names the function that picks the value to sort by. No parentheses: sorted calls it for you.
  • reverse=True puts the largest first. Leave it out to get the smallest first.
  • [:3] is the slice from the last lesson. It keeps the first three items of the sorted list: your three biggest spends.

key=amount_of and reverse=True are keyword arguments: a name, =, then a value. The name says which setting the value is for, so these two can come in either order after the list.

The key function itself is short:

def amount_of(record):
    return record["amount"]

One record goes in, and one value to sort by comes back. To sort by name instead, a key function would return record["item"].

Lists also have a method that sorts: expenses.sort(key=amount_of, reverse=True). It takes the same key and reverse. The difference is that .sort() rearranges the list itself, and gives back None, like append. Your tracker uses sorted, because your Expenses and Latest three sections need expenses in the order you typed it.

A minimal working example

main.py
def print_line(label, amount):
    print(f"{label}: ₦{amount:,}")
 
 
def amount_of(record):
    return record["amount"]
 
 
expenses = [
    {"item": "Bus fare", "amount": 1500},
    {"item": "Lunch", "amount": 2500},
    {"item": "Data bundle", "amount": 3500},
    {"item": "Suya", "amount": 800},
    {"item": "Fuel", "amount": 4200},
]
top_three = sorted(expenses, key=amount_of, reverse=True)[:3]
 
print("Top three spends:")
for record in top_three:
    print_line("  " + record["item"], record["amount"])

Output: Top three spends:, then Fuel: ₦4,200, Data bundle: ₦3,500 and Lunch: ₦2,500, each indented two spaces. The expenses list itself still starts with Bus fare.

Common mistakes

You sort records with no key. Run this:

RECORDS WITH NO KEY · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output
TypeError: '<' not supported between instances of 'dict' and 'dict'

dict is Python's short name for a dictionary, and < is "less than". Sorting works by asking whether one item is less than another, over and over. Numbers and text can answer that. Two dictionaries cannot, so Python stops. Give sorted a key: sorted(expenses, key=amount_of).

You put parentheses after the key's name. Run this:

A KEY WITH PARENTHESES · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output
TypeError: amount_of() missing 1 required positional argument: 'record'

The parentheses call amount_of on the spot, before sorted even starts. That call has no record in it, so Python names the missing 'record'. Remove the parentheses: key=amount_of. Then sorted makes every call itself, each one with a record.

You store what .sort() gives back. Run this:

STORING WHAT SORT GIVES BACK · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

The first line is None. The second shows amounts, now sorted largest first. .sort() rearranged the list itself and gave back nothing, the same trap as append in the lists lesson. So top holds None. If you go on to slice it, for example top[:3], Python stops with an error.

TypeError: 'NoneType' object is not subscriptable

NoneType is the type of None, and "not subscriptable" means you cannot use square brackets on it. Use top = sorted(amounts, reverse=True) for a new list, or write amounts.sort() on a line of its own.

Try it yourself

You will add a section that lists your three biggest spends, biggest first.

  1. Run the starting code below. Look at your Latest three section. It follows the order of your receipt lines, not the size of the amounts.

  2. Under your print_line function and its two blank lines, add amount_of, followed by two blank lines:

    def amount_of(record):
        return record["amount"]

    It now sits between print_line and count_over.

  3. Under your large_spends = count_over(amounts, 3000) line, add this line:

    top_three = sorted(expenses, key=amount_of, reverse=True)[:3]

    Run it. Confirm your report has not changed. The new list exists, but nothing prints it yet.

  4. Find the print() under your Latest three loop. Under it, add these lines:

    print("Top three spends:")
    for record in top_three:
        print_line("  " + record["item"], record["amount"])
    print()

    Run it. Confirm a Top three spends section now follows Latest three, with your three biggest amounts, biggest first. With the amounts given, that is Fuel, Data bundle and Lunch. Confirm your Expenses section kept its order.

  5. Delete , reverse=True from your top_three line. Run it. Confirm the section now shows your three smallest amounts, smallest first. With the amounts given, that is Suya, Bus fare and Lunch. Put , reverse=True back.

  6. Break it on purpose: change key=amount_of to key=amount_of(). Run it. Confirm the console shows a TypeError that names the missing 'record', and none of your report. That line runs before the first print.

  7. Fix it: delete the parentheses so it reads key=amount_of again. Run it. Confirm your report returns, with your top three spends.

TRY IT YOURSELF · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

Your tracker now ranks your spending, biggest first. Its month is still typed by hand, though. The next lesson gets today's date from code someone else wrote.

QUIZ · 3 QUESTIONSCheck what stuckStart the quiz
PART 3 · 07 OF 08❮❯