Home > Back-end >  How to find the difference between two lists of dictionaries for a specific value?
How to find the difference between two lists of dictionaries for a specific value?

Time:06-03

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?

CodePudding user response:

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

CodePudding user response:

Your for loop is not working because you are checking each pair from the two lists - you can restructure your for loop to only append if not found entirely within the other list

new_list = []
for locn_dict in a:
    for country_dict in b:
        if locn_dict['location'] == country_dict['country']:
            break
    else: # This else is with the for, not if
        new_list.append(locn_dict['location'])

Output

['Australia']
  • Related