![](/img/trans.png)
[英]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.