python 44 lines · 7 steps

Flattening nested config into dotted keys

A recursive generator walks nested mappings and lists, joining the path to each leaf into a single flat dictionary.

Explained by highlit
1from collections.abc import Mapping
2from typing import Any, Iterator
3 
4 
5def flatten_config(
6 config: Mapping[str, Any],
7 *,
8 separator: str = ".",
9 list_indices: bool = True,
10) -> dict[str, Any]:
11 return dict(_walk(config, prefix=(), separator=separator, list_indices=list_indices))
12 
13 
14def _walk(
15 node: Any,
16 *,
17 prefix: tuple[str, ...],
18 separator: str,
19 list_indices: bool,
20) -> Iterator[tuple[str, Any]]:
21 if isinstance(node, Mapping):
22 if not node:
23 yield separator.join(prefix), {}
24 return
25 for key, value in node.items():
26 yield from _walk(
27 value,
28 prefix=prefix + (str(key),),
29 separator=separator,
30 list_indices=list_indices,
31 )
32 elif list_indices and isinstance(node, (list, tuple)):
33 if not node:
34 yield separator.join(prefix), []
35 return
36 for index, value in enumerate(node):
37 yield from _walk(
38 value,
39 prefix=prefix + (str(index),),
40 separator=separator,
41 list_indices=list_indices,
42 )
43 else:
44 yield separator.join(prefix), node
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A recursive generator that yields key-value pairs lets you build the final structure lazily and assemble it with one dict() call.
  2. 2Carrying an accumulating prefix tuple down the recursion turns a tree path into a flat composite key.
  3. 3Explicitly handling empty containers preserves information that would otherwise vanish when a branch has no leaves.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Flattening nested config into dotted keys — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code