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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 14 views 0 copies

Python code

19 lines
Python 3.9+
def 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

stdout
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

  1. Use dict.get() combined with "if value is None" for a more concise approach
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.