Unit 4 · Lesson 5

Iterating Over Dictionaries

Loop through keys, values, or both — and work with nested data structures.

Use .keys(), .values(), .items()
Process dict entries in loops
Build dicts from raw data
Work with nested list-of-dict structures

Dictionary Iteration

Three ways to loop through a dictionary:

scores = {"Alice": 95, "Bob": 87, "Charlie": 92} # Loop through keys for name in scores: # or scores.keys() print(name) # Loop through values for score in scores.values(): print(score) # Loop through both (most useful!) for name, score in scores.items(): print(f"{name}: {score}")

Nested Data: List of Dicts

Real-world data often combines lists and dicts:

students = [ {"name": "Alice", "grade": 95}, {"name": "Bob", "grade": 87}, ] for s in students: print(f"{s['name']}: {s['grade']}")
.items() is your best friend — it gives you both key and value in each iteration. Use it whenever you need to process entire dict entries.
Practice Time

Challenges

📋

Challenge 1: Student Report

Guided

Print a formatted report card from a grades dictionary.

Instructions: Loop through grades dict and print each subject and grade. Also calculate and store the average.
Hint: for subject, grade in grades.items(): then print(f"{subject}: {grade}") and total += grade
👑

Challenge 2: Most Popular

Guided

Find the key with the highest value in a dictionary.

Instructions: Find the winner (key with highest value) and max_votes from the votes dict.
Hint: for name, count in votes.items(): then if count > max_votes: max_votes = count; winner = name

Challenge 3: Roster Builder

Solo

Build a dictionary mapping teams to player lists from raw data.

Instructions: Given a list of (player, team) tuples, build rosters dict where each key is a team and each value is a list of player names.
Hint: For each player, team: if team not in rosters: rosters[team] = [] then rosters[team].append(player)
📊

Challenge 4: Data Dashboard

Stretch

Given a list of student dicts, compute per-student and class averages.

Instructions: Each student dict has "name" and "scores" (a list). Calculate each student's average and store in averages dict (name→avg). Also calculate the class_average.
Hint: For each student, avg = sum(s["scores"]) / len(s["scores"]) then averages[s["name"]] = avg and class_total += avg