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'}
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.
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.
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.
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.
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'}]
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