Back to Practice
#0007
Safely Read a Nested Dictionary Value
MediumPython16 min15 XP
Problem
Given a dictionary, a list of keys, and a default value, walk through the nested dictionaries. Return the found value or the default if any key is missing.
Why This Matters
API responses and JSON data are nested. Production code needs to handle missing keys gracefully.
Function Signature
def nested_get(data, keys, default=None):
Examples
Example 1
Inputdata = {"user": {"profile": {"city": "Chennai"}}}, keys = ["user", "profile", "city"]
Output"Chennai"
Every key exists, so the nested value is returned.
Constraints
- Intermediate levels must be dictionaries.
- Return default if any key is missing.
- An empty keys list returns the original data.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Existing nested value
Inputcity inside user/profile
Expected"Chennai"
The function walks one key at a time.
Missing nested key
Inputcountry missing inside profile
Expected"NA"
Missing keys return the default instead of raising KeyError.
Hidden Test Categories
Empty keys listIntermediate value is not a dictionaryDefault value is NoneOne-level dictionary