Hidden Depths

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L4

Problem

A config loader returns settings as a flat dict whose keys encode their depth with dots, like a.b.c for a value 3 levels down. Return the equivalent nested dict, where each dot-separated segment of a key becomes one level deeper and the value lands at the end of its path; a key with no dots stays at the top level.

Each dot marks a level. Rebuild the tree it stands for.

Example 1

Input:

flat = {"d":3,"a.b":1,"a.c":2}

Output:

{"d":3,"a":{"b":1,"c":2}}

Example 2

Input:

flat = {"x.y.z":10}

Output:

{"x":{"y":{"z":10}}}

Worked solution and explanation

What this really is

Strip off the config-loader costume and this is path insertion into a tree of plain dicts, where a later key often lands inside a branch an earlier key already built. Everyone splits on dots. What separates candidates is the walk: for each segment except the last you descend one level, creating a dict only if that level is missing, and the final segment receives the value. Create the level unconditionally and the second key under server.ports wipes the first, so http vanishes and only https survives. Treat the last segment like the rest and the value gets buried under an empty dict.


Break it down

Step 1: Split each key into path segments

'database.host.port' becomes ['database', 'host', 'port']. A key with no dot becomes a single-element list, which is why dotless keys land at the top level with no special case.

Step 2: Walk to the parent, creating levels only when missing

Hold a cursor at the result dict. For each segment except the last, check for a child dict there: create one only if it is missing, then move the cursor into it. That check is what lets a later key like 'a.c' reuse the 'a' dict that 'a.b' already built instead of replacing it.

Step 3: Drop the value at the last segment

Once the cursor sits at the deepest parent, assign the value under the final segment. This is the one line that must live outside the descent loop.


The solution

Iterative path walking
def unflatten(flat: dict) -> dict:
    result = {}
    for key, value in flat.items():
        parts = key.split(".")
        current = result
        for segment in parts[:-1]:
            if segment not in current:
                current[segment] = {}
            current = current[segment]
        current[parts[-1]] = value
    return result

Common follow-up questions