Dictionaries: Labeled Storage

Python for Absolute Beginners · Lesson 13

What you’ll learn

1 / 13

Labels instead of positions

2 / 13

Make a dictionary

student = {"name": "Mia", "age": 9, "grade": "4th"}
print(student)

{'name': 'Mia', 'age': 9, 'grade': '4th'}

Python shows string keys in single quotes — that is just how it displays them, and it means the same thing.

3 / 13

Reading an entry

student = {"name": "Mia", "age": 9, "grade": "4th"}
print(student["name"])
print(student["age"])

Mia
9

Square brackets, just like a list — but with the key instead of a position. A missing key gives a KeyError.

4 / 13

Changing and adding entries

5 / 13

Change and add

student = {"name": "Mia", "age": 9, "grade": "4th"}
student["age"] = 10
print(student)
student["pet"] = "Biscuit"
print(student)

{'name': 'Mia', 'age': 10, 'grade': '4th'}
{'name': 'Mia', 'age': 10, 'grade': '4th', 'pet': 'Biscuit'}

The age entry was replaced, because “age” already existed; the pet entry was added, because it did not.

6 / 13

List or dictionary?

7 / 13

Looping through a dictionary

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

10 / 13

Key takeaways

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.