Home >Backend Development >Python Tutorial >How Can I Recursively Merge Multi-Level Dictionaries in Python?

How Can I Recursively Merge Multi-Level Dictionaries in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 20:42:11360browse

How Can I Recursively Merge Multi-Level Dictionaries in Python?

Merging Multi-Level Dictionaries Deeply

In Python, merging dictionaries recursively while maintaining an unknown depth of nesting can be a challenge. Here's a solution that addresses this issue:

def deep_merge(a: dict, b: dict, path=[]):
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                deep_merge(a[key], b[key], path + [str(key)])
            elif a[key] != b[key]:
                raise Exception('Conflict at ' + '.'.join(path + [str(key)]))
        else:
            a[key] = b[key]
    return a

This function takes two dictionaries as input and recursively merges their contents. It maintains a path to track the current nesting level to provide more precise error messages in case of conflicts.

Example:

dict1 = {1:{'a':{'A'}}, 2:{'b':{'B'}}}
dict2 = {2:{'c':{'C'}}, 3:{'d':{'D'}}}
result = deep_merge(dict1, dict2)

print(result)
# {1:{'a':{'A'}}, 2:{'b':{'B'}, 'c':{'C'}}, 3:{'d':{'D'}}}

Note that deep_merge mutates the first argument, which is why result contains the merged dictionary.

To merge multiple dictionaries without modifying any of them, pass them as keyword arguments:

from functools import reduce
result = reduce(deep_merge, [dict1, dict2, ...], {})

The above is the detailed content of How Can I Recursively Merge Multi-Level Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn