Home > Backend Development > Python Tutorial > How to Perform a Deep Merge of Nested Dictionaries in Python?

How to Perform a Deep Merge of Nested Dictionaries in Python?

DDD
Release: 2024-12-04 02:03:10
Original
930 people have browsed it

How to Perform a Deep Merge of Nested Dictionaries in Python?

Deep Merge of Dictionaries of Dictionaries in Python

Merging multiple dictionaries with nested keys can be a challenging task. Let's consider the following example:

dict1 = {
    1: {"a": {"A"}},
    2: {"b": {"B"}}
}

dict2 = {
    2: {"c": {"C"}},
    3: {"d": {"D"}}
}
Copy after login

The desired output is:

dict3 = {
    1: {"a": {"A"}},
    2: {"b": {"B"}, "c": {"C"}},
    3: {"d": {"D"}}
}
Copy after login

To achieve this deep merge, we can utilize a recursive function:

def merge(a: dict, b: dict, path=[]):
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                merge(a[key], b[key], path + [str(key)])
            else:
                a[key] = b[key]
        else:
            a[key] = b[key]

    return a
Copy after login

This function takes two dictionaries, a and b, and a path that keeps track of the current location in the nested structure. It iterates through the keys in b and checks if the corresponding key exists in a. If the values at that key are both dictionaries, it calls the merge function recursively to merge those sub-dictionaries. Otherwise, it updates the value in a with the value from b.

For the example dicts above, the merge function would produce the desired result:

print(merge(dict1, dict2))
Copy after login

The output would be:

{
    1: {'a': {'A'}},
    2: {'b': {'B'}, 'c': {'C'}},
    3: {'d': {'D'}}
}
Copy after login

Note: This function mutates the first dictionary, a. If you wish to preserve its contents, you can make a copy before merging, e.g., merge(dict(a), b).

The above is the detailed content of How to Perform a Deep Merge of Nested 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template