Dictionaries and Other Collections · practice
Check Keys and Use get()
Bracket lookup is direct and clear when a key is required:
title = book["title"]
If the key is missing, Python raises a
Check membership first
The in
book = {
"title": "Kindred",
"year": 1979,
}
if "creator" in book:
print(book["creator"])
else:
print("Creator missing")
in checks keys, not values. This
"Kindred" in book
is False because "Kindred" is a
Use not in for the opposite check:
if "creator" not in book:
print("Creator missing")
Ask with get()
The .get() also reads a value:
format_name = book.get("format")
When the key is missing, .get() returns None instead of raising a KeyError.
Supply a second
format_name = book.get("format", "unknown")
print(format_name)
# unknown
The dictionary is not changed. .get() only chooses what value the call returns.
Required or optional?
Choose based on the record’s meaning:
Use
book["title"]when every valid book record must have a title.Use
book.get("format", "unknown")when format is optional and the caller has a sensible fallback.Use
"creator" in bookwhen the program needs to take a different action depending on whether the field exists.
Do not replace every bracket lookup with .get(). Silently accepting a missing required key can hide bad data. Safe lookup means making an intentional choice.
What does this program print?
item = {"name": "Compass", "price": 12}
print(item.get("color", "not listed"))
print(len(item))
Task
Read required and optional information from record.
Read the required
"title"with bracket lookup and store it intitle.Use
.get()to read"format"with the fallback"unknown", storing the result informat_name.Use
not into printCreator missingwhen"creator"is absent.Keep the two final report lines.
Expected output:
Creator missing
Title: Kindred
Format: unknown