0%

python比较两个复杂字典

字典结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
dict = {
"family": {
"grandfather": [
"John",
{
"father": "Michael",
"kids": [
{"kid": ("Tom", 10, "M", "123 Street")},
{"kid": ("Lucy", 12, "F", "456 Street")}
]
}
]
}
}

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def compare_dicts(dict1, dict2, path=""):
differences = []

# Check for keys in dict1 not in dict2
for key in dict1:
if key not in dict2:
differences.append(f"Key {path + str(key)} is missing in the second dictionary")
else:
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
differences.extend(compare_dicts(dict1[key], dict2[key], path + str(key) + "->"))
elif isinstance(dict1[key], list) and isinstance(dict2[key], list):
if len(dict1[key]) != len(dict2[key]):
differences.append(f"List length mismatch at {path + str(key)}")
else:
for i, (item1, item2) in enumerate(zip(dict1[key], dict2[key])):
if isinstance(item1, dict) and isinstance(item2, dict):
differences.extend(compare_dicts(item1, item2, path + str(key) + f"[{i}]->"))
elif item1 != item2:
differences.append(f"List item mismatch at {path + str(key)}[{i}]: {item1} != {item2}")
elif isinstance(dict1[key], tuple) and isinstance(dict2[key], tuple):
if dict1[key] != dict2[key]:
differences.append(f"Tuple mismatch at {path + str(key)}: {dict1[key]} != {dict2[key]}")
else:
if dict1[key] != dict2[key]:
differences.append(f"Value mismatch at {path + str(key)}: {dict1[key]} != {dict2[key]}")

# Check for keys in dict2 not in dict1
for key in dict2:
if key not in dict1:
differences.append(f"Key {path + str(key)} is missing in the first dictionary")

return differences

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def main():
dict1 = {
"family": {
"grandfather": [
"John",
{
"father": "Michael",
"kids": [
{"kid": ("Tom", 10, "M", "123 Street")},
{"kid": ("Lucy", 12, "F", "456 Street")}
]
}
]
}
}

dict2 = {
"family": {
"grandfather": [
"John",
{
"father": "Michael",
"kids": [
{"kid": ("Tom", 10, "M", "123 Street")},
{"kid": ("Lucy", 13, "F", "456 Street")}
]
}
]
}
}

differences = compare_dicts(dict1, dict2)
if not differences:
print("没有差异")
else:
print("差异如下:")
for diff in differences:
print(diff)

if __name__ == "__main__":
main()