Flatten a Nested Dict to Dot Notation Keys in Python

Recursively flatten a nested dictionary into a flat dictionary with dot-separated keys using a small recursive function.

Easy Python 3.6+ Aug 9, 2026 Dictionaries & sets 11 views 0 copies

Python code

24 lines
Python 3.6+
def flatten_dict(nested, parent_key='', sep='.'):
    items = {}
    for key, value in nested.items():
        new_key = f"{parent_key}{sep}{key}" if parent_key else key
        if isinstance(value, dict):
            items.update(flatten_dict(value, new_key, sep))
        else:
            items[new_key] = value
    return items


if __name__ == "__main__":
    sample = {
        "user": {
            "name": "Alice",
            "address": {
                "city": "Paris",
                "zip": "75001"
            }
        },
        "active": True,
        "scores": [9, 8]
    }
    print(flatten_dict(sample))

Output

stdout
{'user.name': 'Alice', 'user.address.city': 'Paris', 'user.address.zip': '75001', 'active': True, 'scores': [9, 8]}

How it works

The flatten_dict function walks through every key-value pair in the dictionary. When a value is itself a dictionary, it recurses with the new key prefix joined by the separator. Otherwise it stores the value directly. The parent_key parameter tracks the current key path, and the sep parameter lets you change the separator (e.g., to _ instead of .). Since it returns a new dict, the original nested dict is left unchanged. This pattern works for values of any type, including lists and other immutable objects.

Common mistakes

  • Forgetting to handle empty dictionaries—they produce no keys in the output.
  • Using a separator that might appear in keys themselves, causing collisions.
  • Modifying the original dictionary inside the function—it should return a new one.

Variations

  1. Use `pathlib.Path.read_text` and `json.loads` to flatten a JSON file's contents in one go.
  2. Flatten with an underscore separator (e.g., `user_name`) for use in dataframes or APIs.

Real-world use cases

  • Converting nested JSON API responses into flat structures for CSV export or database inserts.
  • Normalizing configuration dictionaries into environment-variable-style keys for deployment.
  • Simplifying complex nested dicts for logging or debugging output readability.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.