Skip to content
Advertisement

How to find the difference between two lists of dictionaries for a specific value?

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

I want to find the values in the list that are different from each other in terms of location and country. That is, only the list values that differ. That means for example I just want to know, there is no match for Australia

The issue is that it is a list of dictionaries

a = [{'location': 'USA'}, {'location': 'Australia'}]
b = [{'countryID': 1,'country': 'USA'}, {'countryID': 2, 'country': 'UK'}]

With for loops it did not work.

new_list = []
for x in range(len(a)):
        for y in range(len(b)):
            if a[x]["Location"] != b[y]["country"]:
                new_list.append(a[x]["Location"])```

How can I solve the problem?

Advertisement

Answer

Use twice comprehensions:

>>> a = [{'location': 'USA'}, {'location': 'Australia'}]
>>> b = [{'countryID': 1,'country': 'USA'}, {'countryID': 2, 'country': 'UK'}]
>>> s = {dct['country'] for dct in b}
>>> [dct for dct in a if dct['location'] not in s]
[{'location': 'Australia'}]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement