← Back to course
Code Crew G6+ / Week 05 / Friday
5/6
Week 05 Β· Lists and dictionaries

Friday

Counting and combining
// Keeping many values together
⏱ about 30 min

Friday: Counting and combining

The crew has tagged every task this week as build, test or idea. The flight director asks a simple question: how many of each?

Rocket starts three counters, then remembers that new tags appear every week. "I cannot make a variable for every tag forever," he says.

Raven thinks about Thursday. "What do you notice?" she asks. "Each tag is a name, and each count is a number. A name with a number sounds like a dictionary."

Nova sorts glowing tags into piles in the air, and a number appears above each pile. "I found a pattern," she says. "Look up the tag. If it is new, start at zero. Then add one."

Rocket writes one line that does exactly that.

Counting with a dictionary

counts.get(tag, 0) gives the current count, or 0 if the tag is new. Adding 1 and storing it back counts one more. One line handles every tag, even ones you have never seen.

The items() method gives each key and value as a pair, so a for loop can use both.

# tag_count.py
tags = ["build", "test", "idea", "build", "test", "build"]
counts = {}
for tag in tags:
    counts[tag] = counts.get(tag, 0) + 1

for tag, number in counts.items():
    print(f"{tag}: {number}")
build: 3
test: 2
idea: 1
If tags also had "idea" added at the end, what would the idea line show? idea: ____
WHY THIS EXERCISEEach time a tag appears, the loop adds 1 to its count.

A list of dictionaries

Real data often looks like a list of records, where each record is a dictionary. This is exactly the shape the Mission Log will use in week 11.

Inside an f-string that uses double quotes, use single quotes around the key, like entry['day'].

# log_preview.py
log = [
    {"day": 1, "tag": "build", "text": "Built the launch clock"},
    {"day": 2, "tag": "test", "text": "Tested the fuel gauge"},
    {"day": 3, "tag": "build", "text": "Added the docking game"},
]
for entry in log:
    print(f"Day {entry['day']} [{entry['tag']}] {entry['text']}")
print(len(log), "entries")
Day 1 [build] Built the launch clock
Day 2 [test] Tested the fuel gauge
Day 3 [build] Added the docking game
3 entries
What is log[1]["tag"]?
What is log[-1]["day"]?
At your computer
1. Type tag_count.py, save it and run it.
2. Add three more tags to the list, including a brand new one. Run it again.
3. Type log_preview.py, save it and run it. Watch the single quotes inside the f-string.
4. Add a fourth entry for day 4 and run it.
5. Challenge: add a loop that prints only the entries tagged build.

Practice: add up a dictionary

items() gives each key and value together. That makes it easy to add up the values and check each one as you go.

# fuel_tanks.py
tanks = {"A": 40, "B": 75, "C": 20}
total = 0
for name, level in tanks.items():
    total = total + level
    if level < 30:
        print(f"Tank {name} is low")
print("Total fuel:", total)
TRACE FUEL_TANKS.PY
  • Read the question.
  • Tap your answer.
What does the last line show?
Why is only tank C reported as low?
In the loop, what does name hold the first time round?
Change tank B to 25. How many tanks are reported low?
With B at 25, what is the total fuel?
counts = {}. After counts["x"] = counts.get("x", 0) + 1 twice, what is counts["x"]?
StatementTrue or false?
for k, v in d.items() gives each key and its value.?
counts.get(tag, 0) gives 0 for a tag never seen before.?
A list can hold dictionaries as its items.?
log[0]["tag"] reads the tag of the last entry.?
WHY THIS EXERCISElog[0] is the first dictionary, so log[0]["tag"] is the tag of the first entry.

Lists of dictionaries can hold almost any information. You now know the data shape at the heart of Mission Log. Tomorrow is a Crew Quest.

← Thursday