bhylu.com

Advertisements

Access Items

Use square brackets when a key must exist, and get when a missing key has a defined fallback. Those choices communicate different assumptions.

Understand the idea

get does not insert its fallback into the dictionary. A supplied None is different from an absent key, although get without a separate default returns None for both. Use membership or a unique sentinel when the distinction matters. Avoid wrapping the entire application in a broad missing-key exception handler.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

record = {"name": "Mira", "city": None}
print(record.get("phone", "Not recorded"))
print("city" in record, record["city"] is None)

Read the result

The outputs show Not recorded, then True and True. city is present with a missing value.

Try one change

Handle an absent city separately from a recorded empty string and a recorded None value.