Neural Mastery
← Practice
Safe Nested Dictionary Traversaleasy

Safe Nested Dictionary Traversal

easy Python for AI 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Implement defensive nested property lookup (optional chaining) -- essential for safely querying deeply nested REST payloads, GraphQL responses, and LLM structured outputs.

Related Skills

Task

Implement safe_nested_get(data, keys, default=None): walk through keys sequentially within data. If at any stage a key does not exist or the current object is not a dictionary, return default. If keys is empty, return data.

Function Signature

safe_nested_get(data: dict, keys: list[str], default=None)

Examples

Example 1: Deeply Nested Key Found
Input: data = {'user': {'profile': {'name': 'Ada Lovelace'}}} keys = ['user', 'profile', 'name'] default = 'Unknown'
Output: 'Ada Lovelace'
Example 2: Key Missing Along Path
Input: data = {'user': {'id': 42}} keys = ['user', 'email'] default = 'no-email'
Output: 'no-email'

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must never raise KeyError, TypeError, or IndexError during traversal.
  • Returns default whenever traversal cannot proceed.
  • Empty keys list returns data directly.
Python3Saved ✓
def safe_nested_get(data: dict, keys: list[str], default=None):
"""Safely traverse a nested dictionary path without KeyError or TypeError.

Walks down keys in order. If any key is missing or an intermediate
value is not a dict, returns default. If keys is empty, returns data."""
# Your implementation here
pass

Case 1: Deeply Nested Key Found
Input: data = {'user': {'profile': {'name': 'Ada Lovelace'}}} keys = ['user', 'profile', 'name'] default = 'Unknown'
Expected: 'Ada Lovelace'
Case 2: Key Missing Along Path
Input: data = {'user': {'id': 42}} keys = ['user', 'email'] default = 'no-email'
Expected: 'no-email'