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

Python如何比较两个字典列表 获取List2中独有的字典元素

Python两个字典列表差集提取方案

匹配规则说明

比对的唯一匹配依据为两个字段的组合:

  • 字典中固定键zrepcode的取值
  • 字典中除zrepcode外的数字格式id键(如"1"/"3"/"4"等)
    只要上述组合未在List1中出现,对应的List2元素就属于需要提取的差集内容。

实现代码

实现思路是先把List1中所有已存在的标识组合存入集合(集合做存在性判断效率极高),再遍历List2筛选符合条件的元素:

# 原始待比对列表
List1 = [{"3":[{"period":"P13","value":10,"year":2022}],"zrepcode":"55"},{"1":[{"period":"P10","value":5,"year":2023}],"zrepcode":"55"}]
List2 = [{"1":[{"period":"P1","value":10,"year":2023},{"period":"P2","value":5,"year":2023}],"zrepcode":"55"},{"3":[{"period":"P1","value":4,"year":2023},{"period":"P2","value":7,"year":2023}],"zrepcode":"55"},{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]

# 收集List1中所有已存在的(zrepcode, 数字id)组合
exist_pairs = set()
for item in List1:
    zrep_val = item["zrepcode"]
    # 找到当前条目的数字id键
    for key in item:
        if key != "zrepcode":
            exist_pairs.add( (zrep_val, key) )
            break

# 筛选List2中组合不存在于List1的条目
res = []
for item in List2:
    zrep_val = item["zrepcode"]
    for key in item:
        if key != "zrepcode":
            if (zrep_val, key) not in exist_pairs:
                res.append(item)
            break

运行结果

执行上述代码后,res的取值和预期完全一致:

[{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]

方案说明

  • 不需要提前硬编码数字id的键名,自动识别非zrepcode的键作为匹配id,适配动态数字键场景
  • 严格按照双维度匹配规则判断,不会因为id相同但zrepcode不同出现误判
  • 基于集合做存在性校验,数据量较大时运行效率远高于嵌套遍历的写法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 14:15:58