Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the difference between two lists of dictionaries?

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?

like image 983
Chris Avatar asked Aug 28 '14 15:08

Chris


People also ask

How do you compare lists in dictionary?

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.

How do you find the difference between two lists?

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) .

How do you find the difference between lists in Python?

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.

How do you compare two dictionaries in Python?

For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.


1 Answers

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'}]
like image 189
Cory Kramer Avatar answered Oct 11 '22 13:10

Cory Kramer