KatInterview

Convert Nested Dictionary to Dot-Separated Keys

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsrecursioniterationdictionary

Last 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