In more advanced Python applications—like APIs, data processing, or config handling—you often deal with nested dictionaries. These structures can lead to KeyError exceptions when attempting to access keys that may not exist at deeper levels. Handling this gracefully is key to writing fault-tolerant and production-ready code.
def get_user_email(user_data):
try:
return user_data["profile"]["contact"]["email"]
except KeyError as e:
print(f"Missing key in user data: {e}")
return None
# Simulated user data (incomplete)
user1 = {
"profile": {
"name": "Alice",
# "contact" is missing
}
}
email = get_user_email(user1)
print("Email:", email)
get_user_email tries to extract the user’s email from a deeply nested dictionary."profile", "contact", or "email") are missing, a KeyError will be raised.try-except block catches this error and prints which key is missing.None instead of letting the exception crash the program.KeyError at a granular level ensures your app stays robust and fails gracefully.dict.get() for shallow accesscollections.defaultdict or recursive error handling for deep structures