Deep traversal merging of python nested dicts


dict1 = {1: {2: {3: {4: {}}}}}
dict2 = {1: {2: {4: {6: {}}}}}
dict3 = {1: {2: {3: {5: {}}}}}

def deepSearch(dict1, dict2):
    for key in dict2.keys():
        if key not in dict1.keys():
            dict1[key] = dict2[key]
        else:
            deepSearch(dict1[key], dict2[key])

for dictT in [dict2, dict3]:
    deepSearch(dict1, dictT)

print(dict1)
 
 
Use deep traversal to merge nested dicts,
point: If the keys are different, add and traverse other keys. If the keys are the same, enter the value corresponding to the key to traverse.
 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325364277&siteId=291194637