Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Handle missing keys in a dictionary

Safely access nested values in mappings and sequences, returning a default when any key/index is missing.

Python practice16 minError Handling & Edge CasesIntermediateLast updated March 20, 2026

Problem statement

Write get_nested(data, path, default=None) which attempts to retrieve a nested value from data using path. Requirements: - data may be a dictionary or nested combinations of dicts and lists. - path can be either a list/tuple of keys/indices or a dot-separated string (e.g., 'a.b.0.c'). - When following the path: - If the current value is a dict and the next token is a key present in it, continue. - If the current value is a list (or tuple) and the next token is an integer index (string or int), access that index when valid. - If any step is invalid (missing key, index out of range, wrong type), return default without raising an exception. - Return the final value if found. Design for defensive behavior and simple usage in data processing pipelines.

Task

Implement a helper that retrieves a nested value by path, tolerating absent keys or wrong types and returning a default.

Examples

Simple nested dict

Input

get_nested({'a': {'b': 2}}, 'a.b', None)

Output

2

Path 'a.b' retrieves the nested value 2.

Input format

Three arguments: data (dict/list), path (list/tuple of keys or dot-separated string), default (any).

Output format

Return the value found at path or default if any step is invalid.

Constraints

Do not raise exceptions for missing keys or wrong types. Support integer index tokens for list access.

Samples

Sample 1

Input

get_nested({'x': 1}, 'y', 'missing')

Output

missing

Key 'y' is missing; function returns the provided default.