Jos
Jos

Reputation: 69

Find difference of list of dictionary Python

I have 2 Lists in Python;

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

I tried to convert it to set it showed unhashable type: 'dict'

The operation i was trying to do is

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

So what can be done with my list to achieve same functionality? Thanks

Upvotes: 4

Views: 1747

Answers (3)

Param
Param

Reputation: 49

You can make use of ifilterfalse from itertools.

list(itertools.ifilterfalse(lambda x: x in listA, listB)) + list(itertools.ifilterfalse(lambda x: x in listB, listA))

The output will be

[{'b': '4'}, {'a': '3'}]

Upvotes: 0

Jacky Wang
Jacky Wang

Reputation: 3490

We could use dict.items() to get tuples, which 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)

The output is

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

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Do it with simple list comprehension.

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

Upvotes: 7

Related Questions