Flatten JSON to Dot-Keys

Hard ⏱ 18 min 36% acceptance ★★★★★ 4.6
Analytics pipelines flatten nested JSON. Write flatten(data, prefix='') turning {'a': {'b': 1}, 'c': 2} into {'a.b': 1, 'c': 2} recursively — nested dicts extend the key path with dots; every non-dict value lands as a leaf.

Examples

Example 1
Input
flatten({'a': {'b': 1, 'c': {'d': 2}}, 'e': 3})
Output
{'a.b': 1, 'a.c.d': 2, 'e': 3}
Explanation

Paths accumulate through recursion.

Constraints

  • Recursive solution.
  • Lists are treated as leaf values.

Topics

JSONflattening

Companies

DatadogElasticSplunk

Hints

Hint 1

Build the child prefix as f"{prefix}{key}." when descending.

Hint 2

Merge child results with update().

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.