# The Path Inward

> Every setting hides a few levels down. Follow the route, or come back empty.

Canonical URL: <https://datadriven.io/problems/the_path_inward>

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

A service config nests sections inside sections, and `config` holds one such tree. Given `path`, a list of keys naming a single setting's route from the top level inward, return that setting's value. Return `None` the moment the path can no longer be followed, including when it runs into a plain value before the keys run out.

## Worked solution and explanation

### What this really is

Strip the config costume off and this is a guarded walk down a chain of dict lookups. Everyone gets the happy path: start at the top, grab path[0], then path[1], keep going. The part that actually separates people is the failure: somewhere mid-route a key is missing, or worse, the value you just landed on is a plain int or string and the NEXT key tries to index into it. Miss that second case and your function does not return None, it blows up with a TypeError deep inside a config load and takes the whole service start with it.

---

### How to walk it

#### Step 1: Carry one cursor down the tree

Hold one moving reference, starting at config itself. You are not recursing here; you are sliding a pointer down one level at a time, and that single variable is the only state you need.

#### Step 2: Take one key at a time

For each key in path, you want to step into the next section. But before you index, you have to know two things are true: what you are holding is still a dict, and this key actually lives in it.

#### Step 3: Bail out the moment the route dies

The instant either check fails, hand back None and stop. This is the whole game: a missing key and a scalar-where-a-dict-should-be both mean the route died, and both have to exit the same quiet way instead of throwing.

---

### The solution

**Iterative key-path traversal with safe fallback**

```python
def nested_access(config, path):
    current = config
    for key in path:
        if not isinstance(current, dict) or key not in current:
            return None
        current = current[key]
    return current
```

> **Why it stays cheap**
>
> **Time:** O(k) where k is the length of path. Each level is a single average-case O(1) dict lookup, so the work is just the depth you walk, not the size of the config.
> 
> **Space:** O(1). One reference variable slides down the tree; nothing is copied or accumulated.

> **Interviewers watch for**
>
> The tell is the order of that guard. `isinstance(current, dict)` has to come BEFORE `key not in current`, and short-circuit `or` is doing real work: if current is the integer 5432, `5432 not in current` would itself raise TypeError. Candidates who write the key check first look fine on the visible tests and detonate on the `{'db': 5432}` case.

> **Common pitfall**
>
> Reaching for try/except around `current[key]` and only catching KeyError. It feels safe, but a scalar mid-path raises TypeError, not KeyError, so the except clause sails right past it and the exception escapes. The type guard is what closes that hole; the bare KeyError catch only covers half the ways a route can die.

---

## Common follow-up questions

- How would you support a caller-supplied default instead of always returning None? _(Tests adding a default parameter to the function signature.)_
- What changes if a path segment can be a list index, like reaching into items then position 0? _(Tests extending traversal to handle both dict key access and list index access.)_
- How would you write the deep_set twin that creates the path when it does not exist yet? _(Tests building nested dicts on the fly with setdefault chaining.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_path_inward)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). DataDriven is the data engineering interview community. Live code execution in SQL, Python, and Spark sandboxes. Every feature is open to every member.