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:
Your Latest three section follows the order of your receipt lines. Your biggest spends could be anywhere in that list. Now run this:
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:
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:
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.expenseskeeps its order.key=amount_ofnames the function that picks the value to sort by. No parentheses:sortedcalls it for you.reverse=Trueputs 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
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:
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:
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:
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 subscriptableNoneType 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.
-
Run the starting code below. Look at your
Latest threesection. It follows the order of your receipt lines, not the size of the amounts. -
Under your
print_linefunction and its two blank lines, addamount_of, followed by two blank lines:def amount_of(record): return record["amount"]It now sits between
print_lineandcount_over. -
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.
-
Find the
print()under yourLatest threeloop. 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 spendssection now followsLatest three, with your three biggest amounts, biggest first. With the amounts given, that is Fuel, Data bundle and Lunch. Confirm yourExpensessection kept its order. -
Delete
, reverse=Truefrom yourtop_threeline. 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=Trueback. -
Break it on purpose: change
key=amount_oftokey=amount_of(). Run it. Confirm the console shows aTypeErrorthat names the missing'record', and none of your report. That line runs before the firstprint. -
Fix it: delete the parentheses so it reads
key=amount_ofagain. Run it. Confirm your report returns, with your top three spends.
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.