easy +8 pts

Key error handler

Safely access dictionary keys with a flexible default fallback.

Implement a function `safe_get(data, key, default=None)` that returns `data[key]` if the key exists, otherwise returns `default`. The challenge is to handle the `KeyError` raised when the key is missing. Do not use `dict.get` in your implementation; use `try`/`except` to catch the exception. The function should work for any dictionary-like object that raises `KeyError` on missing keys. If `key` is found, return the associated value as is. If `key` is not found, return the `default` value. The `default` parameter is optional; if not provided, it defaults to `None`.

Constraints

Input `data` is a dictionary (or dict-like). `key` is a hashable value. The function should run in O(1) time on average. Do not use the built-in dict.get method.

Example

>>> safe_get({'a': 1}, 'a')
1
>>> safe_get({'a': 1}, 'b')
None
>>> safe_get({'a': 1}, 'b', 0)
0
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Wrap the direct access `data[key]` in a try block.
Catch only `KeyError`, not other exceptions.
Make sure to return `default` in the except block.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.