Dictionaries: Labelled Fields
Unit ID: M03-U03 Estimated active time: 25-35 minutes
Store meaning in keys
course = {
"code": "PY-01",
"title": "Python Foundations",
"hours": 32,
"available": False,
}
A dictionary stores key-value pairs. The keys above explain each field more clearly than positions in a mixed list.
Read and update a value
print(course["title"])
course["hours"] = 30
course["level"] = "beginner"
Assignment to an existing key updates its value. Assignment to a new key adds a field.
Missing keys
print(course["instructor"])
This raises KeyError because the key is absent.
Use .get() when a missing key is an expected possibility:
instructor = course.get("instructor")
print(instructor)
The result is None. You may supply a default display value:
print(course.get("instructor", "Not assigned"))
Do not use a default to hide data that should have been required.
Test keys explicitly
print("title" in course)
print("instructor" in course)
Membership checks dictionary keys.
Inspect dictionary views
print(course.keys())
print(course.values())
print(course.items())
These views expose keys, values, or key-value pairs. Later, loops will process them.
Remove a field
removed_level = course.pop("level")
print(removed_level)
pop() removes the key and returns its value. It raises KeyError if the key is absent unless a default is supplied.
Practice
Create a dictionary for a fictional module with keys id, title, minutes, and complete. Then:
- Read the title.
- Change
completetoTrue. - Add a
notesfield withNone. - Check whether
minutesexists. - Use
.get()to display an absentreviewerfield safely.
Takeaway
Dictionaries represent labelled records. Keys express meaning, and missing-key behaviour should match the task. Next, we will use sets when uniqueness and membership are more important than order.
