Recursive Merge for Python Dict.

Recursive Merge for Python Dict.

When working with Python, you often encounter scenarios where merging dictionaries is required. However, a simple update() or dictionary unpacking ({**dict1, **dict2}) might not suffice when dictionaries contain nested structures. This is where a recursive merge function becomes incredibly useful. In this blog, we’ll explore a Python function, merge_dicts, that merges two dictionaries recursively

Jan 23, 2025
When working with Python, you often encounter scenarios where merging dictionaries is required. However, a simple update() or dictionary unpacking ({**dict1, **dict2}) might not suffice when dictionaries contain nested structures. This is where a recursive merge function becomes incredibly useful.
In this blog, we’ll explore a Python function, merge_dicts, that merges two dictionaries recursively.

What is Recursive Merge?

A recursive merge ensures that:
  1. Shallow Keys: For keys that exist only in one dictionary, their values are directly copied to the merged result.
  1. Nested Dictionaries: For keys that exist in both dictionaries and whose values are themselves dictionaries, the merge is applied recursively to their contents.
This approach ensures that nested structures are merged seamlessly, without overwriting data unnecessarily.

The Code

Here’s the implementation of the merge_dicts function:
def merge_dicts(source, updates): """ Recursively merge two dictionaries. If a key exists in both, and its value is a dictionary, merge them recursively. Otherwise, take the value from `updates`. """ for key, value in updates.items(): # If the value is a dictionary and the key exists in the source as a dictionary, recurse if isinstance(value, dict) and key in source and isinstance(source[key], dict): merge_dicts(source[key], value) else: # Otherwise, set or update the key in the source source[key] = value return source

How It Works

  1. Iterating Through Updates: The function iterates through the updates dictionary.
  1. Handling Nested Dictionaries:
      • If a value in updates is a dictionary and the same key exists in source with a dictionary value, the function calls itself recursively to merge them.
  1. Updating Values: For all other cases, the value from updates overwrites or adds to the source.

Example Usage

Let’s see the function in action:
source = { "a": 1, "b": { "c": 2, "d": 3 }, "e": 4 } updates = { "b": { "d": 30, "e": 40 }, "f": 50 } merged = merge_dicts(source, updates) print(merged)

Output:

{ "a": 1, "b": { "c": 2, "d": 30, "e": 40 }, "e": 4, "f": 50 }

Explanation:

  • The key "b" exists in both source and updates. Since its value is a dictionary, the function merges their contents recursively.
  • Keys "a" and "e" are unchanged as they don’t exist in updates.
  • Key "f" is added from updates.

Why Use Recursive Merge?

  1. Complex Structures: Ideal for deeply nested dictionaries, like configuration files, JSON responses, or hierarchical data.
  1. Preserves Data: Avoids overwriting nested structures, retaining data from both dictionaries.
  1. Customizable: The function can be adapted for more complex merging strategies.

Tips and Best Practices

  1. In-Place Modification: The function modifies the source dictionary in-place. If you want to keep source immutable, create a deep copy before calling the function.
  1. Type Checking: Ensure the function handles cases where keys might not map to dictionaries in one of the inputs.
  1. Error Handling: Consider edge cases, such as non-dictionary inputs or deeply nested structures that could hit Python's recursion limit.

Conclusion

The merge_dicts function provides a powerful way to merge dictionaries recursively. It’s simple, efficient, and fits a wide range of use cases. With a little customization, it can handle even the most complex merging requirements.
Happy coding! 🎉