In Python, we often encounter scenarios where we need to combine multiple nested dictionaries. This task can be challenging, especially when the dictionaries have varying levels of depth and potential conflicts.
To merge dictionaries of dictionaries and maintain the hierarchy, we employ 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)]) elif a[key] != b[key]: raise Exception('Conflict at ' + '.'.join(path + [str(key)])) else: a[key] = b[key] return a
This function accepts two dictionaries, a and b, along with an optional path parameter for tracking the current path in the merged dictionary. It iterates through each key in b and performs the following actions:
Finally, the merged dictionary a is returned.
To merge multiple dictionaries, you can use reduce to combine all dictionaries into a single dictionary:
from functools import reduce reduce(merge, [dict1, dict2, dict3...])
This operation will add the contents of all dictionaries to the first dictionary in the list.
Example:
dict1 = {1:{'a':{'A'}}, 2:{'b':{'B'}}} dict2 = {2:{'c':{'C'}}, 3:{'d':{'D'}}} print(merge(dict1, dict2)) # Output: # {1:{'a':{'A'}}, 2:{'b':{'B'}, 'c':{'C'}}, 3:{'d':{'D'}}}
Note that the resulting dictionary is stored in dict1.
The above is the detailed content of How Can I Efficiently Merge Nested Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!