Collections · Lesson 14 of 25
Dictionaries
Keys and values: a small lookup table.
7 minutes2 games
A dictionary stores key: value pairs in { }. Read a value by its key: student["name"]. .get("x", default) returns a fallback instead of erroring when the key is missing.
Python
student = {"name": "Omar", "level": 3}
student["level"] = 4
student["city"] = "Giza"
print(student["name"], student["level"])
print(student.get("phone", "no phone"))
for key, value in student.items():
print(key, "->", value)| Tool | Use |
|---|---|
| Read; KeyError if missing |
| Read with a fallback |
| Test key membership |
Spot the bug
One line raises a KeyError. Which?
Exercise
Print the price of book from the dictionary.
Expected output: 120
Python
prices = {"pen": 5, "book": 120}
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.