基于Key合并Python嵌套对象:现有代码失效求修复方案
修复嵌套对象中Specs属性的合并问题
看起来你现在卡在了多层嵌套对象的specs合并上,核心需求是根据color、type、description这三个键聚合条目,同时合并并去重specs里的properties内容。先拆解下你现有代码的几个核心问题:
- 层级处理错误:你的输入是多层嵌套结构(
person -> metadata -> car_details),但现有代码直接对顶层数组做groupby,没深入到真正需要合并的car_details层级; - 冗余类型转换:
ast.literal_eval(i['specs'])完全没必要,specs本身就是数组类型,不是字符串; - 未处理重复条目:示例里重复的
["drive", "expensive"]在期望输出中只保留了一个,但你的代码没有去重逻辑; - 结构重构逻辑混乱:
get_specs的返回格式和最终需要的结构不匹配,导致合并后结构出错。
下面是修复后的完整代码,我会同步解释关键逻辑:
import json from itertools import groupby # 用于分组的核心键 GROUP_KEYS = ['color', 'type', 'description'] def get_group_key(item): """生成用于分组的唯一键元组""" return tuple(item.get(key) for key in GROUP_KEYS) def merge_properties(properties_list): """合并properties并去重重复的info条目""" seen_info = set() merged_props = [] for props in properties_list: for prop in props: # 将info转为元组才能存入集合做去重判断 info_tuple = tuple(prop['info']) if info_tuple not in seen_info: seen_info.add(info_tuple) merged_props.append(prop) return merged_props def merge_car_details(car_details): """对同一分组的car_details条目进行合并""" # groupby要求连续相同键,所以先排序 sorted_details = sorted(car_details, key=get_group_key) merged_details = [] for key, group in groupby(sorted_details, key=get_group_key): group_items = list(group) # 收集当前分组下所有的properties all_properties = [spec['properties'] for item in group_items for spec in item['specs']] # 合并并去重 final_props = merge_properties(all_properties) # 用分组内第一个条目作为基础,替换specs为合并后的内容 base_item = group_items[0].copy() base_item['specs'] = [{'properties': final_props}] merged_details.append(base_item) return merged_details def merge_person_data(input_data): """处理顶层的person数据,逐层深入合并""" result = [] for person in input_data: new_person = person.copy() new_metadata = [] for meta in new_person['metadata']: new_meta = meta.copy() # 合并当前metadata下的car_details new_meta['car_details'] = merge_car_details(new_meta['car_details']) new_metadata.append(new_meta) new_person['metadata'] = new_metadata result.append(new_person) return result # 测试你的输入数据 input_data = [ { "person_name": "bob", "metadata": [ { "name": "car", "car_details": [ { "color": "black", "type": "bmw", "specs": [ { "properties": [ {"info": ["sedan", "germany"]}, {"info": ["drive", "expensive"]} ] } ], "description": "amazing car" } ] }, { "name": "car", "car_details": [ { "color": "black", "type": "bmw", "specs": [ { "properties": [ {"info": ["powerful", "convertable"]}, {"info": ["drive", "expensive"]} ] } ], "description": "amazing car" } ] } ] } ] # 执行合并并打印结果 merged_result = merge_person_data(input_data) print(json.dumps(merged_result, indent=2))
关键逻辑说明:
- 逐层遍历处理:从顶层person对象开始,依次深入到
metadata和car_details层级,确保在正确的维度做合并; - 分组键生成:用元组作为分组键,保证相同
color/type/description的条目能被正确聚合; - 去重处理:通过集合记录已出现的
info内容,避免合并后出现重复条目; - 结构保留:合并后保留分组内第一个条目的基础属性,只替换
specs部分,确保输出结构和你的期望完全匹配。
运行这段代码后,就能得到你想要的输出结果了。
内容的提问来源于stack exchange,提问作者Jau L
相关产品推荐
相关产品推荐

