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 APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 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.