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.
Python code
24 linesdef 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
{'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
- Use `pathlib.Path.read_text` and `json.loads` to flatten a JSON file's contents in one go.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.