You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何查找两个字典列表指定键对应值的差异

原代码的错误点
  • 字段名拼写错误:第一个列表的字段是全小写的location,代码中写为大写开头的"Location",运行时会直接抛出KeyError
  • 判断逻辑错误:双层循环中只要两个元素不相等就把a的元素加入结果,会产生大量重复值——只要a中元素和b里任意一个元素不相等就会被追加,哪怕它在b中存在匹配项也会被重复加入
  • 对比方向不全:仅做了a到b的对比,完全没有统计仅存在于b、不存在于a的元素
最优实现方案

优先用集合做差集运算,时间复杂度低,代码简洁不易出错:

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

# 提前提取两边需要对比的字段值,转为集合
a_loc_set = {item["location"] for item in a}
b_country_set = {item["country"] for item in b}

# 计算双向差集
only_in_a_value = a_loc_set - b_country_set  # 仅在a中存在的location值
only_in_b_value = b_country_set - a_loc_set  # 仅在b中存在的country值

print(only_in_a_value) # 输出: {'Australia'}
print(only_in_b_value) # 输出: {'UK'}

如果需要保留原字典结构,直接基于上面生成的集合筛选列表即可:

# 保留a中无匹配的原字典
only_in_a_items = [item for item in a if item["location"] not in b_country_set]
# 保留b中无匹配的原字典
only_in_b_items = [item for item in b if item["country"] not in a_loc_set]

print(only_in_a_items) # 输出: [{'location': 'Australia'}]
print(only_in_b_items) # 输出: [{'countryID': 2, 'country': 'UK'}]
纯循环实现方式

如果不想用集合,要通过双层循环实现,核心逻辑是判断当前元素在对方列表中完全找不到匹配项时才加入结果,而不是遇到一次不相等就追加:

only_in_a_items = []
for item_a in a:
    has_match = False
    for item_b in b:
        if item_a["location"] == item_b["country"]:
            has_match = True
            break
    if not has_match:
        only_in_a_items.append(item_a)

only_in_b_items = []
for item_b in b:
    has_match = False
    for item_a in a:
        if item_b["country"] == item_a["location"]:
            has_match = True
            break
    if not has_match:
        only_in_b_items.append(item_b)

内容的提问来源于stack exchange,提问作者redlightfilms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 08:21:53