Unflatten Dot Keys to Nested Dict in Python
Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.
Python code
21 linesdef unflatten_dot_keys(flat_dict):
result = {}
for flat_key, value in flat_dict.items():
parts = flat_key.split(".")
current = result
for part in parts[:-1]:
current = current.setdefault(part, {})
current[parts[-1]] = value
return result
if __name__ == "__main__":
flat = {
"name": "Alice",
"address.city": "Paris",
"address.zip": "75001",
"employer.name": "ACME",
"employer.location.city": "London",
}
nested = unflatten_dot_keys(flat)
print(nested)
Output
{'name': 'Alice', 'address': {'city': 'Paris', 'zip': '75001'}, 'employer': {'name': 'ACME', 'location': {'city': 'London'}}}
How it works
The function splits each flat key into parts using split('.'), then walks through all parts except the last, setting any missing intermediate keys to a new empty dictionary using setdefault. The final part is assigned the value. This transforms flat mappings like translation dictionaries, config files, or ORM results into nested structures for easier access. The pattern preserves the original insertion order but creates nested dicts on demand, which is safe for overlapping prefixes such as 'employer' and 'employer.location'.
Common mistakes
- Mutating the original dictionary instead of returning a new one.
- Using `dict.get` instead of `setdefault`, which fails to create missing intermediate keys.
- Assuming keys with the same prefix always share the same nesting level.
Variations
- Use recursion to unflatten when keys can contain dots as literal characters.
- Use `collections.defaultdict` with a factory for building nested dicts automatically.
Real-world use cases
- Parsing flattened form submissions (e.g., 'user[name]') into nested request payloads.
- Converting object properties stored as dot-separated keys in a flat database table into JSON documents.
- Restructuring nested configuration trees from environment variables where keys use dots as separators.
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.