我想通过仅比较字典的某些键来找到两个字典列表之间的区别。
a = [
{"fruit": "apple", "colour": "green", "notes":"one a day"},
{"vegetable": "tomato", "colour": "red", "origin": "asia"}
]
b = [
{"fruit": "apple", "colour": "green", "origin": "central asia"},
{"fruit": "strawberry", "colour": "red", "notes":"vitamin c"}
]
在示例中,我想忽略比较逻辑notes,origin但仍将它们保留在输出中。预期结果:
output = [
{"vegetable": "tomato", "colour": "red", "origin": "asia"},
{"fruit": "strawberry", "colour": "red", "notes":"vitamin c"}
]
我尝试使用in条件,但它比较了所有字典键:
difference = [i for i in a if i not in b]
我试图调整这个解决方案,但它比较单个字典条目而不是整个集合的问题:
def equal_dicts(a, b):
ignore_keys = ("notes", "origin")
ka = set(a).difference(ignore_keys)
kb = set(b).difference(ignore_keys)
return ka == kb and all(a[k] == b[k] for k in ka)
for item in a:
if not equal_dicts(a, b):
print('same dictionary')
慕标琳琳
萧十郎
相关分类