Python Dictionary key membership
Detect whether a parcel has a record even when its assigned driver is None.
A simple example
Dictionary key membership
- Start with A = 2
- Do this Look for key A
- Result Present
Syntax
key in drivers
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyFind a parcel whose driver is still unassigned
A dispatch desk registers parcels before assigning drivers. Parcel P7 already has a record with an empty assignment, and the operator must distinguish it from a parcel that has never been registered.
drivers = {"P7": None}
print("Registered" if "P7" in drivers else "Unknown")
Registered
Membership tests the key rather than the driver value.
Find an unassigned booking
A clinic already has booking B12, although a clinician has yet to be assigned. The desk checks whether the identifier has a record before creating one. Is the key already present?
Look for a second ticket
A counter has recorded ticket T2 and receives a query for T3. The desk checks whether the identifier has a record before creating one. Is the key already present?
What to watch for
Testing the truthiness of get cannot distinguish None from an absent key.