python · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
looks up a key safely, so you can keep a .
looks a key up like square brackets do, but if the key is missing it hands back the default instead of crashing. votes.get("pizza", 0) gives 0 until pizza has a vote.
That gives you the tally pattern. For each vote, fetch the count so far with .get(vote, 0), add one and store it back. New keys start at 0, and old ones go up.
The same pattern totals spending per category: add the amount instead of one.
votes = ["pizza", "tacos", "pizza", "curry", "pizza"]
counts = {}
for vote in votes:
counts[vote] = counts.get(vote, 0) + 1
print(counts) Leave the default out and .get() hands back None for a missing key.
guess first
Three lookups, one pair. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
totals = {"food": 10}
print(totals.get("food", 0))
print(totals.get("bus", 0))
print(totals.get("fun"))
print(totals)
your turn
Your turn. Count the socks in the drawer.
Finish the tally line: fetch the count so far for this sock, starting at 0 when its colour is new, then add one.
fix it
The spending report crashes. Can you fix it?
- Read the error. On the very first spend, does
totalshave a"food"key yet? - Square brackets crash on a missing key. You need a lookup that starts each new category at 0.
- On the right of line 6, change totals[category] to totals.get(category, 0), then run.
nailed it
you can count anything now. :D
.get(key, default)never crashes on a missing key.- Tally: fetch with
.get(key, 0), add, then store it back. - Add amounts instead of one to total each category.
new words in your collection
- .get()
- default
- tally
This lesson isn’t saved. A free account remembers every lesson you finish.