[英]How to find the difference between two lists of dictionaries for a specific value?
[英]How to find the difference between two lists of dictionaries?
我有两个词典列表,我想找到它们之间的区别(即第一个列表中存在但第二个列表中存在的内容,以及第二个列表中存在但第一个列表中不存在的内容)。
问题是它是一个字典列表
a = [{'a': '1'}, {'c': '2'}]
b = [{'a': '1'}, {'b': '2'}]
set(a) - set(b)
结果
TypeError: unhashable type: 'dict'
期望的结果:
{'c': '2'}
我该如何做到这一点?
您可以使用in
运算符来查看它是否在列表中
a = [{'a': '1'}, {'c': '2'}]
b = [{'a': '1'}, {'b': '2'}]
>>> {'a':'1'} in a
True
>>> {'a':'1'} in b
True
>>> [i for i in a if i not in b]
[{'c': '2'}]
我想找出它们之间的区别(即第一个列表中存在但第二个列表中存在的内容,以及第二个列表中存在但第一个列表中不存在的内容 )
根据您的定义,您正在寻找对称差异 :
>>> import itertools
>>> a = [{'a': '1'}, {'c': '2'}]
>>> b = [{'a': '1'}, {'b': '2'}]
>>> intersec = [item for item in a if item in b]
>>> sym_diff = [item for item in itertools.chain(a,b) if item not in intersec]
>>> intersec
[{'a': '1'}]
>>> sym_diff
[{'c': '2'}, {'b': '2'}
或者(使用示例中给出的明显差异 ):
>>> a_minus_b = [item for item in a if item not in b]
>>> b_minus_a = [item for item in b if item not in a]
>>> sym_diff = list(itertools.chain(a_minus_b,b_minus_a))
>>> a_minus_b
[{'c': '2'}]
>>> b_minus_a
[{'b': '2'}]
>>> sym_diff
[{'c': '2'}, {'b': '2'}]
你也可以用lambda
过滤 :
如果您想要每个列表中的不同项目:
print filter(lambda x: x not in b,a) + filter(lambda x: x not in a,b)
[{'c': '2'}, {'b': '2'}]
或者只是filter(lambda x: x not in b,a)
以获得元素a
,但不是在b
。如果你不想在内存中创建类型的字典可以使用的完整列表itertools.ifilter
from itertools import ifilter
diff = ifilter(lambda x: x not in b,a)
然后迭代差异:
for uniq in diff:
print uniq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.