Reputation: 69
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
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
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
Reputation: 11134
Do it with simple list comprehension.
>>> [i for i in listA if i not in listB]
[{'b': '4'}]
Upvotes: 7