Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Flatten a nested dictionary into dotted keys

Convert a nested dictionary into a single-level dictionary using dot-separated keys for nested paths.

Python practice25 minList & Dictionary PatternsAdvancedLast updated March 20, 2026

Problem statement

Given a dictionary that may contain nested dictionaries as values, produce a flattened dictionary with dot-separated keys representing the path to each non-dictionary (leaf) value. Nested empty dictionaries should not produce keys in the output. If a key is missing from a record or a value is None, keep the value as-is. Keys may already contain dots; the flattening simply joins keys with a '.' character. Implement flatten_dict(d) that accepts a dictionary d and returns a new dictionary mapping dotted paths to leaf values. Examples of behavior: - {'a': {'b': 1}} -> {'a.b': 1} - {'x': {'y': {}}} -> {} (empty nested dict produces no output) - {'k': [1,2], 'm': {'n': None}} -> {'k': [1, 2], 'm.n': None} Focus on correctness and preserving insertion order of keys encountered during a pre-order traversal.

Task

Write a function that takes a nested dict and returns a flat dict where each key is the path of nested keys joined by dots.

Examples

Basic nesting

Input

flatten_dict({'a': {'b': 1, 'c': 2}, 'd': 3})

Output

{'a.b': 1, 'a.c': 2, 'd': 3}

The nested keys under 'a' are joined to form 'a.b' and 'a.c'. The top-level 'd' remains unchanged.

Input format

A single Python dictionary literal passed to flatten_dict(d).

Output format

A single Python dictionary mapping dotted key strings to values.

Constraints

- Only dict values should be recursively flattened. Other value types (lists, ints, None, etc.) are treated as leaves. - Empty nested dictionaries produce no entries. - Preserve the traversal order of keys (pre-order) when creating the output dictionary.

Samples

Sample 1

Input

flatten_dict({'x': {'y': {'z': 0}}, 'w': {}})

Output

{'x.y.z': 0}

'w' maps to an empty dict so it produces no output; 'x.y.z' holds the leaf value 0.