Build with confidence · 30 min

Capstone · Study tracker

Build and test a CSV report from start to finish.

Read the sample CSV and write totals_by_topic(text). Each record contains a topic and minutes. Strip surrounding whitespace, compare topics by lowercase name, convert minutes to integers, and accumulate repeated topics in a dictionary.

Use a separate reporting function to print topics in alphabetical order, followed by the grand total. Check an empty CSV and a topic repeated with different capitalization. A working report should respond correctly when you change the data.

Follow the example

DictReader maps each row to the topic and minutes fields.

Try it yourself

Complete both functions. Keep the empty-input assertion and add your own check for repeated topics. Print exactly the report shown below.

Target output

math: 30 min
python: 45 min
Total: 75 min
Show a hint

Use topic = row["topic"].strip().lower() and totals.get(topic, 0), then loop over sorted(totals).

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import csv
import io

log = """topic,minutes
Python,25
 Math ,30
python,20
"""

def totals_by_topic(text: str) -> dict[str, int]:
    rows = csv.DictReader(io.StringIO(text))
    totals = {}
    for row in rows:
        topic = row["topic"].strip().lower()
        minutes = int(row["minutes"])
        totals[topic] = totals.get(topic, 0) + minutes
    return totals

def print_report(totals: dict[str, int]) -> None:
    for topic in sorted(totals):
        print(f"{topic}: {totals[topic]} min")
    print(f"Total: {sum(totals.values())} min")

assert totals_by_topic("topic,minutes\n") == {}
assert totals_by_topic("topic,minutes\nCode,2\ncode,5\n") == {"code": 7}
print_report(totals_by_topic(log))