The age entry was replaced, because “age” already existed; the pet entry was added, because it did not.
6 / 13
List or dictionary?
List when order matters and items are alike: a week's temperatures, a shopping list
Dictionary when each item has a name: a student's details, a product's price
Storing labeled data in a list means memorizing that position 0 is the name and position 1 is the age
A dictionary removes that memorizing: the label travels with the value
7 / 13
Looping through a dictionary
A for loop over a dictionary walks its keys
If you also want the values, .items() gives you both at once
for key, value in … unpacks each pair into two loop variables at once
str(value) converts a number to text, because + cannot join text and a number directly
8 / 13
Loop with .items()
student = {"name": "Mia", "age": 10, "grade": "4th"}
for key in student:
print(key)
for key, value in student.items():
print(key + ": " + str(value))
name
age
grade
name: Mia
age: 10
grade: 4th
The first loop prints keys only; the second prints each key and value on its own line.
9 / 13
Hands-on exercise
Make a dictionary for yourself with keys “name”, “age”, and “city”, and print the whole dictionary
Print just the value labeled “city”
Change your age entry to next year's age and print the dictionary again
Add a new entry for your favorite color and print the dictionary
Loop through your dictionary with .items() and print each key and value on its own line
10 / 13
Key takeaways
A dictionary stores entries as key: value pairs inside curly brackets.
Read with dict[key]; a missing key gives a KeyError.
Assigning to an existing key replaces it; assigning to a new key adds it.
Choose a list when order matters, a dictionary when items have labels.
.items() loops through key-value pairs together; str() converts a number to text for joining.
11 / 13
Take the quiz
Take the Lesson 13 quiz — 5 quick questions to check what you learned.
12 / 13
Next lesson
Debugging: Reading Error Messages and Fixing Bugs
13 / 13
Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.