I have two lists of dictionaries and I'd like to find the difference between them (i.e. what exists in the first list but not the second, and what exists in the second list but not the first list).
The issue is that it is a list of dictionaries
a = [{'a': '1'}, {'c': '2'}]
b = [{'a': '1'}, {'b': '2'}]
set(a) - set(b)
Result
TypeError: unhashable type: 'dict'
Desired Result:
{'c': '2'}
How do I accomplish this?
According to your definition, you looking for a Symmetric difference:
Alternatively (using the plain difference as given in your example):
You can use the
in
operator to see if it is in the listYou can also you filter with a
lambda
:If you want the different items in each list:
Or just
filter(lambda x: x not in b,a)
to get the elements ina
but not inb
If you don't want to create the full list of dicts in memory you can useitertools.ifilter
Then just iterate over diff: