Flatten nested JSON to dotted keys
Python data engineering interview problem. Difficulty: intermediate. Pattern: Recursion. About 14 minutes. Part of the Pro drill bank.
Turn a nested dict or list structure into one flat dict whose keys are dotted paths. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Nested API payloads are harder to query than flat records. Dotted paths make each leaf easy to address. Flatten nested dictionaries and lists into one dictionary. Dict keys extend paths with dots, list positions use .0, .1, and empty containers stay as values. Do not modify the input. Write flatten(obj: dict) -> dict. user.name becomes Ann, and the tag list becomes user.tags.0 and user.tags.1; id stays 7. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.
Requirements
- Use dotted paths for nested dict keys.
- Use numeric path segments for list positions.
- Keep None, numbers, strings, booleans and empty containers as leaf values.
Constraints
- The input is JSON-like and the return type is a dict.
- The input object must not be mutated.
Examples
Input: flatten({"user": {"name": "Ann", "tags": ["x", "y"]}, "id": 7}) Output: {'user.name': 'Ann', 'user.tags.0': 'x', 'user.tags.1': 'y', 'id': 7} Dict keys and list positions both become path segments.
Topics: lakebench, python, json, flatten, recursion.
More Python interview questions · All interview problems · Learn data engineering
Flatten nested JSON to dotted keys
Interview-style drill: Turn a nested dict or list structure into one flat dict whose keys are dotted paths.
Implement `flatten(obj: dict) -> dict` that turns a nested JSON-like dict into a flat dict. - A value inside a dict is reached with `key.subkey`. - A value inside a list is reached with its position: `key.0`, `key.1`. - An **empty** dict or list is kept as the value itself (`{"a": {}}` becomes `{"a": {}}`). - `None`, numbers, strings and booleans are leaf values. The input must not be modified. An empty input dict gives an empty dict.