×

python · level 2 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.