在不知道键的情况下,可以使用递归方法来排除深度差异中的字典路径。下面是一个示例代码:
def exclude_paths(dict1, dict2):
excluded_paths = []
def compare_dicts(dict1, dict2, path=''):
if type(dict1) != dict or type(dict2) != dict:
return
keys1 = set(dict1.keys())
keys2 = set(dict2.keys())
# 检查dict1中是否有dict2中没有的键
for key in keys1.difference(keys2):
excluded_paths.append(path + key)
# 递归比较字典的值
for key in keys1.intersection(keys2):
compare_dicts(dict1[key], dict2[key], path + key + '/')
compare_dicts(dict1, dict2)
return excluded_paths
使用方法:
dict1 = {
'key1': {
'key2': {
'key3': 'value1',
'key4': 'value2'
},
'key5': 'value3'
},
'key6': 'value4'
}
dict2 = {
'key1': {
'key2': {
'key3': 'value1',
'key4': 'different_value'
},
'key5': 'value3'
},
'key7': 'value5'
}
excluded_paths = exclude_paths(dict1, dict2)
print(excluded_paths) # 输出:['key1/key2/key4', 'key6', 'key7']
在上面的示例中,我们定义了exclude_paths
函数来获取排除的路径列表。该函数内部定义了一个递归函数compare_dicts
,用于比较字典的键和值。
首先,我们检查字典的类型,如果不是字典,则返回。然后,我们获取字典的键集合,并且通过差集操作找到dict1中有而dict2中没有的键,将这些键添加到excluded_paths
列表中。
接下来,我们通过交集操作找到dict1和dict2中共有的键,并递归调用compare_dicts
函数比较对应键的值。在递归调用时,我们通过添加键和斜杠来更新路径。
最后,我们调用exclude_paths
函数传入两个字典,并打印出排除的路径列表。在上面的示例中,输出为['key1/key2/key4', 'key6', 'key7']
,表示在dict2中不存在的路径为key1/key2/key4
、key6
和key7
。