我有两份字典清单,我想把它们合并。当字典出现在两个列表中时,我想在字典中添加一个“置信度”键,以反映词典在两个列表中都存在。
列表-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'}
]发布于 2021-09-28 10:31:23
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将是您的结果
发布于 2021-09-28 10:47:27
您可以使用集合理解来收集列表中每个字典的“键”元素。然后,您可以循环遍历所有的键,并检查一个键是否在两个列表中。
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)发布于 2021-09-28 10:59:26
您可以使用intersection和symmetric_difference函数在set上完全避免原始循环
# Shortened key names for brevity
a = [{"key": "a"}, {"key": "b"}, {"key": "c"}]
b = [{"key": "a"}, {"key": "d"}, {"key": "e"}]
# Turn both lists into sets
a_keys = {entry["key"] for entry in a}
b_keys = {entry["key"] for entry in b}
# Add elements that are in both sets with confidence set to 1
result = [{"key": key, "confidence": 1} for key in a_keys.intersection(b_keys)]
# Add elements that are not in both sets
result += [{"key": key} for key in a_keys.symmetric_difference(b_keys)]将导致:
[{'confidence': 1, 'key': 'a'},
{'key': 'b'},
{'key': 'd'},
{'key': 'c'},
{'key': 'e'}]注意,元素顺序将随着它们通过set而发生变化。
https://stackoverflow.com/questions/69248732
复制相似问题