Dictionaries and Other Collections · practice
Write Functions for Dictionary Records
Chapter 8 gave
book = {
"title": "Kindred",
"category": "novel",
"year": 1979,
}
A formatting function can receive that record:
def catalog_line(item):
return f"{item['title']} | {item['category']} | {item['year']}"
The item holds one dictionary during the call. Bracket lookups read its required fields.
line = catalog_line(book)
print(line)
This prints:
Kindred | novel | 1979
The dictionary defines a record shape
catalog_line expects an item with three keys:
"title""category""year"
That expected set of fields is the record’s shape. Python does not declare it separately here. The function and the data must agree.
This record works:
map_item = {
"title": "City map",
"category": "reference",
"year": 2026,
}
This one is missing a required key:
incomplete = {
"title": "City map",
"year": 2026,
}
Calling catalog_line(incomplete) raises a "category".
That is not a reason to use .get() everywhere. If every catalog item requires a category, the incomplete record should be fixed.
Keep responsibilities separate
The dictionary stores facts. The function decides how to format them. The caller decides whether to print, store, or compare the returned line.
line = catalog_line(book)
print(line)
This is the same boundary you practiced with
What does summary contain?
def item_summary(item):
return f"{item['name']}: {item['stock']}"
record = {"name": "Compass", "stock": 8}
summary = item_summary(record)
Task
Complete catalog_line(item) so it returns the item’s required fields in this form:
Kindred | novel | 1979
Read "title", "category", and "year" from the
Keep the existing call and final print.