Find Difference in a List of Python Dictionaries

I have 2 lists in Python;

listA = [{'b': '3'}, {'b': '4'}]
listB = [{'a': '3'}, {'b': '3'}]

      

I tried converting it to set it showing a non-typed type: 'dict'

The operation I tried to do is -

list[(set(listA)).difference(set(listB))]

      

So what can I do with my list to achieve the same functionality? Thanks to

+3


source to share


2 answers


We could use dict.items()

to get tuples that could be converted to set

type

setA = set(chain(*[e.items() for e in listA]))
setB = set(chain(*[e.items() for e in listB]))

print setA.symmetric_difference(setB)

      



Output signal

set([('a', '3'), ('b', '4')])

      

+1


source


Do it with a simple list comprehension.



>>> [i for i in listA if i not in listB]
[{'b': '4'}]

      

+7


source







All Articles