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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A recursive generator that yields key-value pairs lets you build the final structure lazily and assemble it with one dict() call.
- 2Carrying an accumulating prefix tuple down the recursion turns a tree path into a flat composite key.
- 3Explicitly handling empty containers preserves information that would otherwise vanish when a branch has no leaves.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/flattening-nested-config-into-dotted-keys-explained-python-8d40/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.