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
Release: 2024-12-04 20:42:11
Original
339 people have browsed it

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
Copy after login

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'}}}
Copy after login

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, ...], {})
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template