<p>我有两个字典列表,我想合并它们。当两个列表中都有词典时,我想为词典添加一个“信心”键,以反映词典在两个列表中都存在</p>
<p><strong>列表-1</strong></p>
<pre><code>lst1 = [
{'key': 'data_collected.service_data'},
{'key': 'gdpr.gdpr_compliance'},
{'key': 'disclosure_of_information.purpose_of_disclosure'},
{'key': 'opt_out.choice_of_opt_out'}
]
</code></pre>
<p><strong>列表2</strong></p>
<pre><code>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'}
]
</code></pre>
<p><strong>当我在代码下面运行时,我没有得到正确的输出</strong></p>
<pre><code>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)
</code></pre>
<p><strong>输出应该是这样的</strong></p>
<pre><code>[
{'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'}
]
</code></pre>
<p><code>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)</code></p>
<p>lst1将是您的结果</p>