如何将Python嵌套字典列表按name字段中的数值键重构?
问题需求
我需要将一个特定格式的嵌套字典列表重构为指定输出格式,核心是提取每个条目name字段中的数值部分作为父键,将对应分类的条目归集到该父键下。
输入示例
input = [ { "A": { "values": [ { "id": "1234", "name": "109 - Apple", "description": "Apple" }, { "description": "Mango", "id": "5678", "name": "17892 - Mango" } ] } }, { "B": { "values": [ { "id": "4563", "name": "109 - Apple", "description": "Apple" }, { "description": "Mango", "id": "9767", "name": "17892 - Mango" } ] } } ]
期望输出格式
output = [ { "109": [ { "A": { "id": "1234", "name": "109 - Apple", "description": "Apple" } }, { "B": { "id": "4563", "name": "109 - Apple", "description": "Apple" } } ], "17892": [ { "A": { "description": "Mango", "id": "5678", "name": "17892 - Mango" } }, { "B": { "description": "Mango", "id": "9767", "name": "17892 - Mango" } } ] } ]
实现方案
以下是Python代码实现,直接按需求完成数据重构:
input_data = [ { "A": { "values": [ { "id": "1234", "name": "109 - Apple", "description": "Apple" }, { "description": "Mango", "id": "5678", "name": "17892 - Mango" } ] } }, { "B": { "values": [ { "id": "4563", "name": "109 - Apple", "description": "Apple" }, { "description": "Mango", "id": "9767", "name": "17892 - Mango" } ] } } ] # 初始化结果容器 result_dict = {} for group in input_data: # 获取当前分组的标识(A/B) group_key = next(iter(group.keys())) entries = group[group_key]["values"] for entry in entries: # 从name中提取数值作为父键 parent_key = entry["name"].split(" - ")[0] # 父键不存在则初始化空列表 if parent_key not in result_dict: result_dict[parent_key] = [] # 将当前条目按分组格式加入对应列表 result_dict[parent_key].append({group_key: entry}) # 包装成要求的输出结构 output = [result_dict] print(output)
代码逻辑说明
- 初始化空字典
result_dict,用于按提取的数值键存储分类后的条目 - 遍历输入中的每个分组(A/B组),提取分组标识和对应的条目列表
- 对每个条目,拆分
name字段获取前面的数值作为父键 - 将条目以
{分组标识: 条目}的格式添加到对应父键的列表中 - 最后将结果字典包装成列表,匹配期望的输出格式
内容的提问来源于stack exchange,提问作者Vivek Kumar
相关产品推荐
相关产品推荐

