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.
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.
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
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.