我有两个字典列表,我想合并它们。当两个列表中都有词典时,我想为词典添加一个“信心”键,以反映词典在两个列表中都存在
列表-1
lst1 = [
{'key': 'data_collected.service_data'},
{'key': 'gdpr.gdpr_compliance'},
{'key': 'disclosure_of_information.purpose_of_disclosure'},
{'key': 'opt_out.choice_of_opt_out'}
]
列表2
lst2 = [
{'key': 'child_data_protection.parent_guardian_consent'},
{'key': 'ccpa.ccpa_compliance'},
{'key': 'disclosure_of_information.purpose_of_disclosure'},
{'key': 'opt_out.choice_of_opt_out'}
]
当我在代码下面运行时,我没有得到正确的输出
res = []
for x in lst1:
for y in lst2:
if x["key"] == y["key"]:
if x not in res and y not in res:
res.append({"key": x["key"], "confidence": 1})
else:
if x not in res and y not in res:
res.append(x)
res.append(y)
print(res)
输出应该是这样的
[
{'key': 'data_collected.service_data'},
{'key': 'gdpr.gdpr_compliance'},
{
'key': 'disclosure_of_information.purpose_of_disclosure',
'confidence': 1
},
{
'key': 'opt_out.choice_of_opt_out',
'confidence': 1
},
{'key': 'child_data_protection.parent_guardian_consent'},
{'key': 'ccpa.ccpa_compliance'}
]
您可以使用set comprehension收集列表中每个字典的“关键”元素。然后可以循环遍历所有键,并检查两个列表中是否都有一个键
可以使用
set
上的intersection
和symmetric_difference
函数完全避免原始循环:将导致:
请注意,当元素通过
set
时,元素顺序将发生变化lst1.extend(i for i in (i if i not in lst1 else lst1[lst1.index(i)].update({'confidence': 1}) for i in lst2) if i is not None)
lst1将是您的结果
相关问题 更多 >
编程相关推荐