How to Catch KeyError with a Default Value in Python Dictionaries
Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.
Python code
19 linesdef get_value(data, key, default=None):
"""
Safely get a value from a dictionary, returning a default if the key
is missing or the value is None.
"""
try:
value = data[key]
return value if value is not None else default
except KeyError:
return default
if __name__ == "__main__":
config = {"host": "localhost", "port": 8080, "debug": None}
print(get_value(config, "host", "unknown")) # Expected: localhost
print(get_value(config, "port", 0)) # Expected: 8080
print(get_value(config, "debug", False)) # Expected: False (None -> default)
print(get_value(config, "missing", "not set")) # Expected: not set
Output
localhost
8080
False
not set
How it works
The get_value function uses a try/except block to catch KeyError when a key is absent from the dictionary. It also explicitly checks for None values with value is not None, so a missing key or a None value both fall back to the provided default. This differs from the built-in dict.get() method, which only handles missing keys but not None values. The if __name__ == "__main__" guard ensures the test lines run only when the script is executed directly, not when imported. This pattern is useful when you need distinct behavior for missing keys versus None values in config or payload data.
Common mistakes
- Forgetting that dict.get() does not convert None to a default, so you need an explicit check
- Catching KeyError with a bare except: that also hides other errors like TypeError
- Assuming 'in' checks and try/except are interchangeable when the dictionary is large and accessed many times
Variations
- Use dict.get() combined with "if value is None" for a more concise approach
- Use a collections.defaultdict with a callable factory for repeated missing-key patterns
Real-world use cases
- Reading environment or config dictionaries where optional keys may be absent or set to None.
- Parsing JSON API responses to safely extract optional fields without crashing on missing data.
- Processing user settings or preferences where defaults should apply when values are unset or null.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.