Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing

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.

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.

Requirements

  • List positions are used as keys, starting at 0.
  • Leaf values are returned unchanged.

Constraints

  • Keys of the input dicts are strings without dots.
  • Nesting depth is at most 50.
  • The input is not 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

intermediate

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.