Convert Nested Dictionary to Dot-Separated Keys
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests ability to traverse nested data structures and transform hierarchical key-value pairs into a flat representation using path notation.
You are given a dictionary that may contain other dictionaries nested within it. Your task is to transform this nested structure into a flat dictionary where each key represents the full path from the root to a value, with path components separated by dots.
For example, if the input is {"a": {"b": 1}}, the output should be {"a.b": 1}.
Rules
- Traverse all nested dictionaries and construct dot-separated paths for keys at each level
- Non-dictionary values (numbers, strings, booleans, lists,
None, etc.) are leaf values and should appear in the output under their full path - An empty dictionary
{}is treated as a leaf value, not as a container to expand - Lists are not flattened—they remain as-is in the output
- All keys should be converted to strings when building paths
- If the input dictionary is empty, return an empty dictionary
Constraints
- The input dictionary may be empty
- Nesting depth: 0 to 100 levels
- Total number of keys across all levels: 0 to 10,000
- Keys may be strings or other types that can be converted to strings
- Values may be of any type (int, float, str, bool, list, dict, None, etc.)
Examples
Example 1
Input: flatten_dict({'a': {'b': 1}})
Output: {'a.b': 1}
Example 2
Input: flatten_dict({'a': {'b': 1, 'c': 2}, 'd': 3})
Output: {'a.b': 1, 'a.c': 2, 'd': 3}
Example 3
Input: flatten_dict({'user': {'profile': {'name': 'Ada', 'age': 36}}, 'active': True})
Output: {'user.profile.name': 'Ada', 'user.profile.age': 36, 'active': True}
Example 4
Input: flatten_dict({})
Output: {}
Hints
Hint 1
Think of the nested dictionary as a tree where each dictionary is a node and leaf values are at the endpoints
Hint 2
You can solve this iteratively using a stack to avoid recursion depth limits
Hint 3
Track the path from root to current position as you traverse, then join the path components when you reach a leaf
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The nested dictionary can be viewed as a tree structure where each non-empty dictionary is an internal node and all other values (including empty dictionaries) are leaves. We need to perform a tree traversal that tracks the path from root to each leaf, then output each leaf under its complete dot-separated path.
An iterative solution using an explicit stack avoids Python's recursion depth limit, which matters for deeply nested inputs.
The algorithm maintains a stack of (path, value) pairs:
- Start with the root: push
(empty_path, input_dict)onto the stack - While the stack is not empty:
- Pop the current
(path, value)pair - If the value is a non-empty dictionary, it's an internal node: push each child onto the stack with the child's key appended to the path
- Otherwise, it's a leaf: write it to the result under the dot-joined path (if the path is non-empty)
- Pop the current
- Push children in reverse order so they pop in their original order, maintaining insertion order in the output
Why empty dictionaries are treated as leaves: If {"a": {}} were treated as an internal node to expand, it would have no children and would vanish from the output. By treating it as a leaf, we preserve the information.
Why we check elif path: The root itself should not be written to the output. This guard ensures that a top-level empty dict produces {} rather than {"": {}}.
Correctness
- Every value reachable from the root is visited exactly once with its complete key path
- Only leaf values are written to the output; internal nodes (non-empty dicts) are expanded but never written
- Path components are joined with dots to form the output keys
- The traversal order (depth-first with children processed in order) matches what a recursive solution would produce
Complexity
Let N be the total number of nodes (dictionaries plus leaf values) and D be the maximum nesting depth.
- Time: O(N · D) worst case. Each node is visited once, and building/joining paths takes O(D) time per node. For typical shallow structures, this is effectively O(N).
- Space: O(N · D) for the stack and stored paths in the worst case, plus O(N) for the output dictionary.
The iterative approach with an explicit stack handles deeply nested structures without hitting recursion limits.
Solution
from typing import Dict
def flatten_dict(obj: Dict[str, object]) -> Dict[str, object]:
result = {}
stack = [((), obj)]
while stack:
path, value = stack.pop()
if isinstance(value, dict) and value:
items = list(value.items())
for key, child in reversed(items):
stack.append((path + (str(key),), child))
elif path:
result[".".join(path)] = value
return result