Update a Deeply Nested Dict Safely

Hard ⏱ 18 min 39% acceptance ★★★★★ 4.9
Write a function set_nested(d, keys, value) where keys is a list of keys describing a path (e.g. ["a", "b", "c"]), and value is the value to place at that path. Create any missing intermediate dicts along the way, then set the final key to value. Mutate d in place and return it.

Examples

Example 1
Input
d = {}; set_nested(d, ['a', 'b', 'c'], 42); d
Output
{'a': {'b': {'c': 42}}}
Explanation

Every missing level is created as an empty dict, then the leaf is set.

Example 2
Input
d = {'a': {'x': 1}}; set_nested(d, ['a', 'b'], 2); d
Output
{'a': {'x': 1, 'b': 2}}
Explanation

Existing sibling keys are preserved.

Constraints

  • keys is a non-empty list.
  • Existing untouched branches must be preserved.

Topics

Dictionariesnested dictssetdefault

Companies

CiscoIntel

Hints

Hint 1

Walk keys[:-1], using `current = current.setdefault(k, {})` at each step.

Hint 2

Then set `current[keys[-1]] = value`.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.