pythonadvanced10 minutes

Predict the Output of Recursive Nested Dictionary Merge with Side Effects

Analyze the given Python function that performs a recursive merge of nested dictionaries with side effects on mutable inputs. Predict the exact output of the code including the final printed dictionaries.

Challenge prompt

Given the following Python code which merges two dictionaries recursively, with in-place modifications, predict the printed output after calling merge_dicts on two nested dictionaries with overlapping keys.

Guidance

  • Understand how recursion is used to merge dictionaries at nested levels.
  • Pay close attention to in-place mutations versus copied values.
  • Trace the dictionary references carefully to see which parts get modified.

Hints

  • Remember that updating a dictionary in-place affects all references to that dictionary.
  • Consider cases where values are dictionaries in both dicts vs. non-dictionary keys.
  • Keep track of how new keys are added and how existing keys are overwritten.

Starter code

def merge_dicts(d1, d2):
    for k, v in d2.items():
        if k in d1:
            if isinstance(d1[k], dict) and isinstance(v, dict):
                merge_dicts(d1[k], v)
            else:
                d1[k] = v
        else:
            d1[k] = v
    return d1


a = {'x': 1, 'y': {'a': 10, 'b': 20}}
b = {'y': {'b': 30, 'c': 40}, 'z': 3}

result = merge_dicts(a, b)
print('a:', a)
print('b:', b)
print('result:', result)

Expected output

a: {'x': 1, 'y': {'a': 10, 'b': 30, 'c': 40}, 'z': 3} b: {'y': {'b': 30, 'c': 40}, 'z': 3} result: {'x': 1, 'y': {'a': 10, 'b': 30, 'c': 40}, 'z': 3}

Core concepts

recursiondictionary mutationnested data structures

Challenge a Friend

Send this duel to someone else and see if they can solve it.