0%

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 . Sometimes that is useful because a required field really is absent. Optional information needs a different plan.

Check membership first

The in checks :

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 , not a key.

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 to choose a more useful fallback:

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 book when 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.

  1. Read the required "title" with bracket lookup and store it in title.

  2. Use .get() to read "format" with the fallback "unknown", storing the result in format_name.

  3. Use not in to print Creator missing when "creator" is absent.

  4. Keep the two final report lines.

Expected output:

Creator missing
Title: Kindred
Format: unknown