Skip to content
GreenSnippets

Flatten a nested dictionary

Turn nested dicts into a single-level dict with dotted keys, handy for config and logging.

Python
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 flat

Example / expected output

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.