如何按天对presentation去重并生成结构一致的字典列表
实现思路
- 先将原始字典中
presentations字段的所有条目按day值分组,得到每个天对应的所有演示条目列表 - 统计所有天的演示条目的最大数量,该值就是需要生成的新字典数量
- 遍历每个索引位,为每个索引位生成一个结构完全和原始字典一致的新字典:新字典的
time、category字段直接复制原始字典的值,presentations列表则从每个天的分组列表中取出对应索引位的条目(如果该索引位存在条目就加入,不存在则跳过) - 所有生成的新字典汇总后就是最终结果
代码实现
from collections import defaultdict # 原始数据 raw_data = [ { "time": "04:00-20:59", "category": 1, "presentations": [ {"presentation": "ABC", "day": 7}, {"presentation": "DEF", "day": 7}, {"presentation": "GHI", "day": 8}, {"presentation": "JKL", "day": 8}, {"presentation": "MNO", "day": 9}, {"presentation": "PQR", "day": 9}, {"presentation": "STU", "day": 9}, ] } ] result = [] for item in raw_data: # 按day分组 day_groups = defaultdict(list) for pres in item["presentations"]: day_groups[pres["day"]].append(pres) # 按day升序排列分组,保证结果顺序符合预期 sorted_days = sorted(day_groups.keys()) # 计算需要生成的新字典数量 max_count = max(len(v) for v in day_groups.values()) # 生成每个新字典 for i in range(max_count): new_pres = [] for day in sorted_days: if i < len(day_groups[day]): new_pres.append(day_groups[day][i]) # 构造新字典,保留原有其他字段 new_item = {k:v for k,v in item.items() if k != "presentations"} new_item["presentations"] = new_pres result.append(new_item) # 打印结果验证 import json print(json.dumps(result, indent=2, ensure_ascii=False))
运行上述代码输出的结果和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者Anthony
相关产品推荐
相关产品推荐

