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.

Medium Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

21 lines
Python 3.9+
def 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

stdout
{'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

  1. Use recursion to unflatten when keys can contain dots as literal characters.
  2. 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

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.