Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Access a nested dictionary safely

Traverse nested dictionaries by a sequence of keys and return a value or a default when any key is missing.

Python practice13 minDictionaries & SetsIntermediateLast updated March 18, 2026

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

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 1

Input

get_nested({'user': {'profile': {'name': 'Eve'}}}, ['user', 'profile', 'name'])

Output

Eve

Traverse user -> profile -> name to get 'Eve'.