python - 我有 2 个列表,我想合并它们,答案应该如下所示

标签 python python-3.x list dictionary concatenation

我有两个字典列表,我想合并它们。当两个列表中都存在字典时,我想向字典添加一个“置信度”键,以反射(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/

相关文章:

python - pip 安装的奇怪行为

performance - 为什么 List.foldBack 和 List.fold 一样快

java - 代码可以在eclipse中运行,但不能在javac中运行

python - 在列表中移动头部和尾部 1 步

python - 如何禁用 python 3.x 中的 ssl 检查?

python - Django读取pdf文件内容

python - 从 django 渲染中显示 html 中的字典

python - 导入错误: No module named tastypie. API

python - Python 2.7x86-Windows 7 机器中的错误 : "Unable to find vcvarsall.bat" when installing lingpy1. 0.1

python - 使用 sympy 解析字符串时出现意外行为