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?
Method #1 : Using "==" operator ( Only keys Unordered ) For the case in which just the keys of dictionaries are unordered, and the ordering in list is in correct way, the test can be done using “==” operator.
The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) .
Use set. difference() to Find the Difference Between Two Lists in Python. The set() method helps the user to convert any iterable to an iterable sequence, which is also called a set. The iterables can be a list, a dictionary, or a tuple.
For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.
You can use the in
operator to see if it is in the list
a = [{'a': '1'}, {'c': '2'}]
b = [{'a': '1'}, {'b': '2'}]
>>> {'a':'1'} in a
True
>>> {'a':'1'} in b
True
>>> [i for i in a if i not in b]
[{'c': '2'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With