Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Update a nested dictionary safely

Set a value deep inside a nested dictionary, creating intermediate dicts as needed.

Python practice15 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Write update_nested(d, keys, value) that updates the dictionary d so that the nested path specified by the list keys points to value. If intermediate keys don't exist, create dicts for them. If an intermediate key exists but its value is not a dict, replace it with a dict to continue the path. The function should return the modified dictionary d. keys is guaranteed to be a non-empty list.

Task

Implement a helper to set a value at a nested path, handling missing intermediate keys and non-dict intermediate values.

Examples

Create a nested path

Input

update_nested({}, ['x', 'y', 'z'], 1)

Output

{'x': {'y': {'z': 1}}}

Intermediate dicts are created to set z to 1.

Input format

A dict d, a non-empty list of keys (keys), and a value to set.

Output format

The dict d after the update (returned).

Constraints

keys is a non-empty list. Keys may be any hashable type. Overwrite non-dict intermediate values to continue the path.

Samples

Sample 1

Input

update_nested({'a': 1}, ['a', 'b'], 2)

Output

{'a': {'b': 2}}

Existing non-dict value for 'a' is replaced with a dict to set 'b'.