Problem No 16
Access a nested dictionary safely
Medium≈ 13 minute session
Lesson guide
What this Python exercise practices
Access a nested dictionary safely is a intermediate practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 13 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Intermediate
- Estimated time
- 13 minutes
Practice path
Summary
Traverse nested dictionaries by a sequence of keys and return a value or a default when any key is missing.
Problem statement
Given a nested dictionary and a list of keys, return the value found by following the keys in order. If any key is missing or an intermediate value is not a dictionary (mapping), return the provided default. The function should not raise exceptions for missing keys or wrong types. The keys parameter will be provided as a list (or other iterable) of keys to follow. The default parameter should be returned when the lookup cannot continue.
Task
Implement a helper that safely retrieves a value from nested dictionaries without raising exceptions when intermediate keys are missing or values are not mappings.
Examples
Basic nested lookup
Input
get_nested({'a': {'b': 2}}, ['a', 'b'])
Output
2
Explanation
Follow 'a' to get {'b': 2}, then 'b' to get 2.
Input format
A dictionary (possibly nested), an iterable of keys, and an optional default value.
Output format
The value found at the nested location or the default. If the value is None, the runner treats it as an empty string when comparing.
Constraints
Do not assume all intermediate values are dicts. Keys may be of any hashable type. The function should be robust and not modify the input.
Samples
Sample input 0
get_nested({'user': {'profile': {'name': 'Eve'}}}, ['user', 'profile', 'name'])
Sample output 0
Eve
Explanation 0
Traverse user -> profile -> name to get 'Eve'.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.