Flatten a nested dictionary
Turn nested dicts into a single-level dict with dotted keys, handy for config and logging.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
def flatten_dict(data, parent="", sep="."):
flat = {}
for key, value in data.items():
path = f"{parent}{sep}{key}" if parent else str(key)
if isinstance(value, dict) and value:
flat.update(flatten_dict(value, path, sep))
else:
flat[path] = value
return flatExample / expected output
flatten_dict({"db": {"host": "x", "port": 5432}, "debug": True})
# {'db.host': 'x', 'db.port': 5432, 'debug': True}How it works
Walks nested mappings and joins the path with a separator. Lists are kept as values. The reverse operation needs a choice about how to treat keys that already contain the separator, so this snippet only flattens.
Related snippets
- Python Tested
Group items by a key
Collect a list of records into a dictionary of lists keyed by a field or function result.
- Python Tested
Safely read a deeply nested value
Walk a path through nested dicts and lists and return a default instead of raising KeyError.
- Python Tested
Token bucket rate limiter
Allow bursts but cap the sustained request rate with a small thread-safe token bucket.
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.

