Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the difference between 2 lists that contain dictionaries [duplicate]

Tags:

python

list

list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

Is there a way to get the difference between those two lists?

Basically, I need a scaleable way to get the differences between 2 lists that contain dictionaries. So I'm trying to compare those lists, and just get a return of {'key3': 'item3'}

like image 336
narhz Avatar asked Nov 11 '18 00:11

narhz


People also ask

How do I compare a list of dictionaries?

In the lists of dictionaries you need to compare each dict in your first list to each list in your second dict if there is no structure in the dictionaries. If you have a fixed structure, sort the list of dictionaries according to some key value pair and then start eliminating the different ones.

How do you find the difference between two dictionaries in Python?

Given two dictionaries dic1 and dic2 which may contain same-keys, find the difference of keys in given dictionaries. Code #1 : Using set to find keys that are missing. Code #2 : Finding keys in dict2 which are not in dict1.

How are lists different from dictionaries write two differences?

A list refers to a collection of various index value pairs like that in the case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and values. We can create a list by placing all the available elements into a [ ] and separating them using “,” commas.

How do I compare two lists in Python?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.


1 Answers

You could use a list comprehension:

list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]

print([x for x in list2 if x not in list1])

Which will give [{'key3': 'item3'}]

like image 144
Simon Avatar answered Sep 23 '22 15:09

Simon