Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Deep merge nested dictionaries

Merge two dictionaries recursively, combining nested mappings instead of overwriting them.

Python practice25 minList & Dictionary PatternsAdvancedLast updated March 20, 2026

Problem statement

Implement deep_merge(dict_a, dict_b) that returns a new dictionary representing dict_a merged with dict_b. Rules: (1) Keys present only in one dict are included as-is. (2) If a key exists in both and both values are dictionaries, recursively deep-merge them. (3) If a key exists in both and at least one value is not a dictionary, the value from dict_b overwrites the one from dict_a. Do not mutate the input dictionaries; always return a new dictionary.

Task

Write a deep_merge function that merges two dictionaries recursively: when a key exists in both and both values are dicts, merge them; otherwise the second dict's value overwrites the first's.

Examples

Merge with nested dicts

Input

deep_merge({'x': 1, 'y': {'a': 10}}, {'y': {'b': 20}, 'z': 3})

Output

{'x': 1, 'y': {'a': 10, 'b': 20}, 'z': 3}

y is merged recursively; x and z are preserved/added.

Input format

Two dictionaries, dict_a and dict_b.

Output format

A new dictionary representing the deep merge of dict_a and dict_b.

Constraints

Dictionaries may contain nested dictionaries. Other value types should be treated as atomic and overwritten by dict_b when keys collide.

Samples

Sample 1

Input

deep_merge({'a': {'b': 1}}, {'a': {'c': 2}})

Output

{'a': {'b': 1, 'c': 2}}

Nested keys under 'a' are merged.