Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 927
Jos Avatar asked Feb 04 '23 07:02

Jos


2 Answers

Do it with simple list comprehension.

>>> [i for i in listA if i not in listB]
[{'b': '4'}]
like image 197
Ahsanul Haque Avatar answered Feb 15 '23 14:02

Ahsanul Haque


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')])
like image 24
Jacky1205 Avatar answered Feb 15 '23 15:02

Jacky1205