如何找到特定值的两个字典列表之间的差异?

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

我有两个字典列表,我想找出它们之间的区别(即第一个列表中存在但第二个列表中不存在的内容,以及第二个列表中存在但第一个列表中不存在的内容)。

我想在列表中找到在位置和国家/地区方面彼此不同的值。也就是说,只有不同的列表值。这意味着例如我只想知道,澳大利亚没有匹配项

问题是它是一个字典列表

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

使用 for 循环它不起作用。

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"])```

我该如何解决这个问题?

使用两次理解:

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

你的 for 循环不起作用,因为你正在检查两个列表中的每一对 - 你可以重组你的 for 循环,以便仅在未完全在另一个列表中找到时才追加

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

输出

['Australia']