我有两个字典列表,我想合并它们。当两个列表中都存在字典时,我想向字典添加一个“置信度”键,以反射(reflect)该字典在两个列表中都存在。
列表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收集列表中每个词典的“关键”元素。然后您可以循环遍历所有键并检查某个键是否在两个列表中。
keys_1 = {d["key"] for d in lst1}
keys_2 = {d["key"] for d in lst2}
output = []
for k in keys_1 | keys_2:
d = {"key": k}
if k in keys_1 and k in keys_2:
d["confidence"] = 1
output.append(d)
关于python - 我有 2 个列表,我想合并它们,答案应该如下所示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69248732/