medium +20 pts

Unflatten JSON dict

Turn a flat dotted-key dictionary back into a nested structured dictionary.

Write a function `unflatten(flat)` that takes a dictionary `flat` whose keys are strings. Each key may contain one or more dots (`.`) that separate levels of a nested dictionary. The corresponding value should be placed at the deepest level. If a key has no dots, it is a top-level key. All intermediate nested values must be dictionaries. The input is guaranteed to be non-empty and contain at least one dotted key. Return the reconstructed nested dictionary. You may assume there are no conflicting paths (e.g., `'a'` and `'a.b'` will not both appear). The order of keys in the output does not matter. For example, `unflatten({'a.b.c': 1, 'a.b.d': 2, 'e': 3})` should return `{'a': {'b': {'c': 1, 'd': 2}}, 'e': 3}`. Implement the function exactly as specified. The function should work for any depth (at least up to 100 levels) and any number of keys.

Constraints

- 1 ≤ len(flat) ≤ 1000 - Each key is a non-empty string consisting of lowercase letters and dots, not starting or ending with a dot, and no consecutive dots. - Values can be any JSON-compatible type (int, float, str, bool, list, dict, None). - No two keys produce a conflict where one is a prefix of another (if `a` is a key, no key starts with `a.`). - Depth (number of segments after splitting by '.') ≤ 100.

Example

>>> unflatten({'a.b.c': 1, 'a.b.d': 2, 'e': 3})
{'a': {'b': {'c': 1, 'd': 2}}, 'e': 3}
>>> unflatten({'x': 10})
{'x': 10}
>>> unflatten({'a.b': {'k': 1}, 'a.c': [1,2]})
{'a': {'b': {'k': 1}, 'c': [1,2]}}
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split each key by '.' and traverse/create nested dictionaries level by level.
Treat the last segment as the key where the value is assigned.
Use a separate root dictionary and maintain a reference as you descend.
You can use the `setdefault` method to avoid overwriting existing intermediate dictionaries.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.