以下是一个比较两个字典列表的解决方法的代码示例:
def compare_dicts(list1, list2, key):
result = []
for dict1 in list1:
for dict2 in list2:
if dict1[key] == dict2[key]:
result.append((dict1, dict2))
return result
# 示例数据
list1 = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
list2 = [{'name': 'Alice', 'age': 28}, {'name': 'Charlie', 'age': 30}]
# 比较基于'name'值的字典列表
result = compare_dicts(list1, list2, 'name')
for dict1, dict2 in result:
print(f"Matched dicts: {dict1}, {dict2}")
输出结果:
Matched dicts: {'name': 'Alice', 'age': 25}, {'name': 'Alice', 'age': 28}
在上面的示例中,compare_dicts
函数接受两个字典列表list1
和list2
,以及一个键key
作为参数。它会遍历两个列表中的字典,并比较指定键的值。如果两个字典的值相等,则将它们添加到结果列表中。最后,返回结果列表。
在示例数据中,我们比较了基于'name'值的字典列表,并打印了匹配的字典对。