# Unflatten Keys

> Dots in the key names. Rebuild the structure.

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

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a flat dict whose keys use dot notation like 'a.b.c', build and return a nested dict where each dot segment becomes a nested key.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **recursive dict construction** from flat dot-notation keys. It probes whether a candidate can navigate nested dicts, creating intermediate levels as needed, a pattern common in config management and JSON manipulation.

---

### Break down the requirements

#### Step 1: Split each key on dots to get the path segments

The key `'database.host.port'` becomes `['database', 'host', 'port']`.

#### Step 2: Walk the nested dict, creating intermediate dicts as needed

For each segment except the last, ensure a dict exists at that level. Set the value at the final segment.

---

### The solution

**Iterative path walking with dict creation**

```python
def unflatten(flat: dict) -> dict:
    result = {}
    for key, value in flat.items():
        parts = key.split(".")
        current = result
        for i in range(len(parts) - 1):
            segment = parts[i]
            if segment not in current:
                current[segment] = {}
            current = current[segment]
        current[parts[-1]] = value
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n * d) where n is the number of keys and d is the average depth (number of dot segments).
> 
> **Space:** O(n * d) for the nested dict structure.

> **Interviewers Watch For**
>
> Correctly handling the last segment differently (assigning the value instead of creating a nested dict). This is where off-by-one errors in the loop range matter.

> **Common Pitfall**
>
> If two keys conflict (e.g., `'a.b' = 1` and `'a.b.c' = 2`), the first sets `a.b` to an integer and the second tries to nest inside it. Handling this conflict gracefully is a design decision worth discussing.

---

## Common follow-up questions

- How would you handle array indices like 'a.0.b'? _(Tests creating lists at numeric segments instead of dicts.)_
- How would you implement the reverse (flatten a nested dict)? _(Tests recursive traversal with path accumulation.)_
- What if keys could contain escaped dots? _(Tests splitting on unescaped dots only, requiring more sophisticated parsing.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/unflatten_keys)
- [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). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.