All posts
postJune 6, 2026

Python dict.get() with default — never raise KeyError again

#python#dict#best-practices
python
user = {"id": 1, "email": "alice@x.com"}

# Crashes with KeyError
# print(user["phone"])

# Safe: returns "n/a"
print(user.get("phone", "n/a"))

# Common DE pattern: safe default for optional fields
country = user.get("country", "unknown")
tags    = user.get("tags", [])
score   = user.get("score", 0)

Accessing a missing key in a dict with brackets raises KeyError, which crashes your script. dict.get(key, default) returns the default value instead — no crash, no exception, just a sensible fallback.

In data engineering you constantly read records where some fields might be missing — optional metadata, nullable database columns, varying API responses. dict.get() with a default is the difference between a robust pipeline and one that crashes on every edge case.