Neural Mastery
← Practice
Flatten Nested Dictionary with Delimitersmedium

Flatten Nested Dictionary with Delimiters

medium Python for AI 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Convert deeply nested JSON dictionaries into flat dot-delimited key-value maps for serialization and tabular export.

Related Skills

Task

Implement flatten_dict(nested, sep="."): recursively traverse nested, constructing keys by concatenating path segments with sep. Return a flat dictionary mapping leaf values to full dotted path strings. Empty sub-dictionaries map to {}.

Function Signature

flatten_dict(nested: dict, sep: str = ".") -> dict

Examples

Example 1: Multi-level Nested Dict
Input: nested = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} sep = '.'
Output: {'a': 1, 'b.c': 2, 'b.d.e': 3}
Example 2: User Record
Input: nested = {'user': {'name': 'Alex', 'age': 30}} sep = '_'
Output: {'user_name': 'Alex', 'user_age': 30}
Example 3: Already Flat Dict
Input: nested = {'x': 10, 'y': 20} sep = '.'
Output: {'x': 10, 'y': 20}

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Default separator is ".".
  • Handles arbitrary nesting depth.
Python3Saved ✓
def flatten_dict(nested: dict, sep: str = ".") -> dict:
"""Flatten an arbitrarily nested dictionary into a single-level dictionary
with keys joined by separator sep."""
# Your implementation here
pass

Case 1: Multi-level Nested Dict
Input: nested = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} sep = '.'
Expected: {'a': 1, 'b.c': 2, 'b.d.e': 3}
Case 2: User Record
Input: nested = {'user': {'name': 'Alex', 'age': 30}} sep = '_'
Expected: {'user_name': 'Alex', 'user_age': 30}
Case 3: Already Flat Dict
Input: nested = {'x': 10, 'y': 20} sep = '.'
Expected: {'x': 10, 'y': 20}