Python字典生成优化:将列表内多对象合并为单个对象
Python字典生成函数修正:合并列表内的键值对对象
我写了一个生成字典的Python函数,但输出不符合预期。目前输出里的"Individual"字段是包含多个单键值对对象的列表,我需要这个列表只放一个整合了所有键值对的对象。
当前输出:
{ "Individual": [ { "FullName": null }, { "City": null }, { "AddressLine1": null }, { "State": null }, { "PostCode": null }, { "Gender": null } ], "AdditionalQuestion": null }
期望输出:
{ "Individual": [ { "FullName": null, "City": null, "AddressLine1": null, "State": null, "PostCode": null, "Gender": null } ], "AdditionalQuestion": null }
原函数代码:
def template(data): def get_names(item): name_entry = None if "properties" in item: properties = item['properties'] if properties: name_entry = {item['name'] : [get_names(prop) for prop in properties if prop is not None and get_names(prop) is not None]} else: bad_names = ["id$","_link"] if item['name'] not in bad_names: name_entry = {item['name']: None} if name_entry: return name_entry data_list = [get_names(item) for item in data if get_names(item) is not None and get_names(item) is not None] data_dict = {} for item in data_list: data_dict.update(item) return data_dict
输入示例:
[{"name": "Individual", "properties": [{"name": "FullName"},{"name": "City"},{"name": "AddressLine1"},{"name": "State"},{"name": "PostCode"},{"name": "Gender"}]},{"name": "SigningDate"}]
问题分析与修正
原函数在处理带properties的项时,会把每个子属性的单键值对字典单独加入列表,导致"Individual"对应列表里有多个小字典。我们需要把这些子属性的键值对合并成一个大字典,再放到列表中。
修改后的函数代码:
def template(data): def get_names(item): name_entry = None if "properties" in item: properties = item['properties'] if properties: # 创建空字典整合所有子属性的键值对 combined_dict = {} for prop in properties: if prop is not None: prop_entry = get_names(prop) if prop_entry: combined_dict.update(prop_entry) # 将整合后的字典放入列表 name_entry = {item['name']: [combined_dict]} else: bad_names = ["id$","_link"] if item['name'] not in bad_names: name_entry = {item['name']: None} if name_entry: return name_entry data_list = [get_names(item) for item in data if get_names(item) is not None] data_dict = {} for item in data_list: data_dict.update(item) return data_dict
修改说明
- 处理
properties时,不再直接生成包含多个单键值对字典的列表,而是先创建combined_dict合并所有子属性的键值对。 - 遍历每个子属性,调用
get_names获取其键值对,并用update方法合并到combined_dict中。 - 最后将
combined_dict放入列表,作为item['name']对应的值。 - 简化了
data_list中的重复判断条件。
内容的提问来源于stack exchange,提问作者Artificial_Float
相关产品推荐
相关产品推荐

