Collections
Dictionaries and key lookup
Store named values in a dictionary, read keys safely, and update entries.
Lesson 20 of 63
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page4 sections
A dictionary maps unique keys to values. Access a known key with square brackets. Assign to a key to add or replace a value.
student = {"name": "Sam", "sessions": 3}
print(student["name"])
student["sessions"] = 4
student["minutes"] = 25
print(student)Sam
{'name': 'Sam', 'sessions': 4, 'minutes': 25}Handle a missing key
Looking up a missing key with square brackets raises KeyError. get() returns a default value instead. You can loop over items() to visit each key and value.
student = {"name": "Sam", "sessions": 3}
print(student.get("minutes", 0))
for key, value in student.items():
print(f"{key}: {value}")0 name: Sam sessions: 3
Why this works
A dictionary looks up a value by its key rather than by a numeric position. Keys identify the meaning of each value, which makes a record such as a student easier to read than a list of unrelated positions. Updating an existing key replaces its value; assigning a new key adds an entry.
Practice
Build a dictionary with title and minutes keys for one lesson. Print both values, update minutes, and use get() for a missing notes key.
What does student.get("minutes", 0) return if minutes is absent?
Reveal answer
It returns the default value 0.
Try another case
If record = {"minutes": 20}, what do record.get("minutes", 0) and record.get("goal", 30) return?
Check your answer
Reveal answer
They return 20 and 30, respectively.
Your progress
Reveal the check answer or reach the end to complete this lesson.