A customer profile requires an ID but may omit a nickname.
What You Need to Understand
Direct indexing mapping[key] signals absence by raising KeyError. mapping.get(key, fallback) treats missing keys as an expected case and returns the fallback. Both return the stored value when a key exists.
When to Use It
A customer profile requires an ID but may omit a nickname.
Step-by-Step Python Example
profile = {"id": 501, "name": "Maya"}
customer_id = profile["id"]
nickname = profile.get("nickname", "Guest")
print(customer_id, nickname)
How the Example Works
The ID is required so direct indexing is suitable. The nickname is optional, so get() supplies Guest.
Example Output
501 Guest
True
None
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
record = {"status": None}
print("status" in record)
print(record.get("status", "unknown"))
Important Behavior and Edge Cases
A present key storing None is not the same as a missing key. Test key in mapping when that difference matters.
Try It Yourself
Make email a required key and phone an optional one, then test a missing required value.
Common Beginner Mistakes
- A present key storing
Noneis not the same as a missing key. Testkey in mappingwhen that difference matters. - Applying the example without a clearly defined policy for missing keys, matching identifiers, or validating external values.
Key Takeaways
- Direct indexing
mapping[key]signals absence by raisingKeyError. - The ID is required so direct indexing is suitable.
- A present key storing
Noneis not the same as a missing key.