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"}} }
The desired output is:
dict3 = { 1: {"a": {"A"}}, 2: {"b": {"B"}, "c": {"C"}}, 3: {"d": {"D"}} }
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
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))
The output would be:
{ 1: {'a': {'A'}}, 2: {'b': {'B'}, 'c': {'C'}}, 3: {'d': {'D'}} }
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!