easy +8 pts

Nested get with dotted path

Safely extract values from nested dictionaries using a dotted path and a default fallback.

Write a function `nested_get(data, path, default=None)` that takes a nested dictionary `data`, a string `path` of keys separated by dots, and an optional `default` value. It should traverse the dictionary following the keys in order. If the full path exists, return the value at that location. If at any point a key is missing (or the current value is not a dictionary), return `default` instead. An empty `path` should return `data` itself.

Constraints

- `data` is either a dictionary or any value (not necessarily a dict). - `path` is a string; it may be empty. - Dictionaries may be nested arbitrarily deep. - Time complexity: O(k) where k is the number of dots in path (number of keys).

Example

>>> nested_get({'a': {'b': {'c': 42}}}, 'a.b.c')
42
>>> nested_get({'a': {'b': {'c': 42}}}, 'a.b.x')
None
>>> nested_get({'a': {'b': 1}}, 'a.b', 'missing')
1
>>> nested_get({}, '')  # returns {} (the data itself)
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `path.split('.')` to get the list of keys; handle empty path separately.
Keep a reference to the current value as you loop through keys.
If the current value isn't a dictionary, you can't go deeper—return default.
If a key is missing (use `if key in current` or try/except), return default.
If you reach the end of the key list, return the current value (or default if None).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.