检查字典列表中是否匹配字典,如果匹配,则添加值 True 或 False



我想比较两个字典列表,如果字典匹配,则在第二个字典列表中添加一个键/值True;如果它们不匹配,则将关键字/值False添加到字典的第二列表中。

当前代码:

list_dict1 = [{'animal': 'Dog', 'age': '3'}, {'animal':'Horse', 'age': '6'}]
list_dict2 = [{'animal': 'Dog', 'age': '3'}, {'animal':'Horse', 'age': '8'}]
for d1 in list_dict1:
for d2 in list_dict2:
if d1 == d2:
d2['match'] = True
else:
d2['match'] = False

电流输出:

list_dict2 = [{'animal': 'Dog', 'age': '3', 'match': False},
{'animal': 'Horse', 'age': '8', 'match': False}]

期望输出:

list_dict2 = [{'animal': 'Dog', 'age': '3', 'match': True},
{'animal': 'Horse', 'age': '8', 'match': False}]

我假设这不起作用的原因是,在每次迭代中,list_dict2都会发生变化,这意味着循环中没有匹配,因为我正在添加一个新值。有什么想法可以继续吗?

解决方案的问题是您再次覆盖结果。

我只需要查看第二个列表,然后检查每个项目是否都在第一个列表中,如下所示:

for d1 in list_dict2:
if d1 in list_dict1:
d1['match'] = True
else:
d1['match'] = False
print(list_dict2)

输出:

[{'animal': 'Dog', 'age': '3', 'match': True},
{'animal': 'Horse', 'age': '8', 'match': False}]

最新更新