如何在一个列表中找到字典,但在另一个列表中找不到

时间:2018-10-02 10:05:57

标签: python python-3.x list dictionary

假设我们有2个字典L1和L2列表。

我想列出L2中但L1中没有的词典列表。就我而言,我有L1是L2的子集,所以不确定是否可以使用该事实进行任何优化。

2 个答案:

答案 0 :(得分:4)

您可以使用列表理解:

L1 = [{1: 2, 2: 3}, {2: 3, 3: 4}]
L2 = [{1: 2, 2: 3}, {4: 5, 5: 6}]
print([d for d in L2 if d not in L1])

这将输出:

[{4: 5, 5: 6}]

或者,如果您有大量的字典,则应将L1转换为一组元组,以便高效地查找成员资格:

set1 = set(tuple(d.items()) for d in L1)
print([d for d in L2 if tuple(d.items()) not in set1])

答案 1 :(得分:2)

解决方案

[_dict for _dict in l1 if _dict not in l2]

这将得到位于l1但不在l2中的字典

相关问题