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
相关产品推荐
相关产品推荐

