基于label键从dict列表提取重复项并按规则保留原条目
问题解决:提取字典列表的重复项并保留指定条目
需求
给定一个字典列表,需基于label字段完成两个操作:
- 提取所有重复条目(每个
label仅保留一条记录,其余均为重复项) - 移除重复条目时,优先移除
headings值为True的条目;若同一label下全为headings=True的条目,则保留最后一条,其余作为重复项。
输入数据
records = [ {"label": "x", "headings": False, "key": 300}, {"label": "x", "headings": True, "key": 301}, {"label": "x", "headings": False, "key": 302}, {"label": "x", "headings": False, "key": 303}, {"label": "y", "headings": False, "key": 304}, {"label": "y", "headings": True, "key": 305}, {"label": "z", "headings": True, "key": 306}, {"label": "z", "headings": True, "key": 307}, ]
解决方案代码
kept_records = {} duplicate_records = [] for record in records: label = record["label"] if label not in kept_records: kept_records[label] = record else: existing_record = kept_records[label] # 已保留的是headings=False,直接将当前记录加入重复项 if not existing_record["headings"]: duplicate_records.append(record) else: # 已保留的是headings=True,检查当前记录的headings if not record["headings"]: # 替换保留条目,原条目移到重复项 duplicate_records.append(existing_record) kept_records[label] = record else: # 都是headings=True,原条目移到重复项,保留当前条目 duplicate_records.append(existing_record) kept_records[label] = record # 输出重复项 print("提取的重复项:") for item in duplicate_records: print(item)
运行结果
提取的重复项列表如下:
[ {"label": "x", "headings": False, "key": 300}, {"label": "x", "headings": True, "key": 301}, {"label": "x", "headings": False, "key": 302}, {"label": "y", "headings": True, "key": 305}, {"label": "z", "headings": True, "key": 306}, ]
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

