Merge two JSON-like config dicts with overrides

Python data engineering interview problem. Difficulty: intermediate. Pattern: Dictionaries. About 15 minutes. Part of the Pro drill bank.

Service config is a nested dict. A deploy overlay should override matching keys and leave unspecified keys from the base intact, including nested maps.

Applications read a base configuration and then apply overrides. Overrides should replace values, but nested settings should be merged and not wiped out. Merge two dictionaries so that keys in override win. When both values for a key are dictionaries, merge them again in the same way. Do not change the inputs. Return the merged dictionary. Write deep_merge(base, override). Merging {'a': 1, 'b': {'c': 2}} with {'b': {'d': 3}, 'e': 4} gives {'a': 1, 'b': {'c': 2, 'd': 3}, 'e': 4}. Merging {} with {'x': 1} gives {'x': 1}. The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Keys from override replace keys from base.
  • If both values are dictionaries, merge them recursively.
  • Keep keys that appear in only one dictionary.
  • Do not change the input dictionaries.

Constraints

  • Values may be numbers, text, lists or other dictionaries.
  • A non-dictionary value in override replaces the base value completely.

Examples

Input: deep_merge({'a': 1, 'b': {'c': 2}}, {'b': {'d': 3}, 'e': 4}) Output: {'a': 1, 'b': {'c': 2, 'd': 3}, 'e': 4} This input follows the stated rules and produces this output.

Topics: lakebench, python, JSON-like-data.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Merge two JSON-like config dicts with overrides

Interview-style drill: Merge a base config dict with an override dict, letting override values win at every nesting level.

Merge two JSON-like dicts so overlay keys win, recursively for nested dicts.