元素数量变化时如何将table_array转换为指定格式字典
问题描述
需要将给定的表格列名数组name和表格内容数组table_array转换为指定结构的字典模板,当前代码在元素添加环节出现问题。
原始变量(已修正语法错误)
name = ['Type', 'No.of Cores', 'Section(mm²)'] table_array = [ [{'Type': '07BN4-AF'}, {'No.of Cores': '1'}, {'Section(mm²)': '1.5-630'}], [{'Type': '07BN4-AF'}, {'No.of Cores': '2、5'}, {'Section(mm²)': '1.0-240'}], [{'Type': '07BN4-AF'}, {'No.of Cores': '3-4'}, {'Section(mm²)': '1.0-300'}], [{'Type': 'H07RN8-F'}, {'No.of Cores': '2-5'}, {'Section(mm²)': '1.0-6.0'}], [{'Type': 'TNEFR/TNEFRZ'}, {'No.of Cores': '1'}, {'Section(mm²)': '6-185'}], [{'Type': 'TNEFR/TNEFRZ'}, {'No.of Cores': '2-5'}, {'Section(mm²)': '1.5-150'}], [{'Type': 'TNEFR/TNEFRZ'}, {'No.of Cores': '6-24'}, {'Section(mm²)': '1.5-2.5'}], [{'Type': 'TNEERP/TNEERPZ'}, {'No.of Cores': '1'}, {'Section(mm²)': '6-185'}], [{'Type': 'TNEERP/TNEERPZ'}, {'No.of Cores': '2-5'}, {'Section(mm²)': '1.5-150'}], [{'Type': 'TNEERP/TNEERPZ'}, {'No.of Cores': '6-24'}, {'Section(mm²)': '1.5-2.5'}], [{'Type': 'SJYCW-BQ'}, {'No.of Cores': '3、4、5、3+1、3+2'}, {'Section(mm²)': '4-35'}], [{'Type': 'YCT'}, {'No.of Cores': '3、4、5、3+1、3+2'}, {'Section(mm²)': '4-35'}], [{'Type': 'SJYCR'}, {'No.of Cores': '3、4、5、(3+1)、(3+2)'}, {'Section(mm²)': '4-35'}] ]
目标结构
template = { 'parameters_row': row_index, # 总数据行数 'parameters_inf': { '0': { 'Type': '07BN4-AF', 'No.of Cores': '1', 'Section(mm²)': '1.5-630' }, '1': { 'Type': '07BN4-AF', 'No.of Cores': '2、5', 'Section(mm²)': '1.0-240' }, # ... 其余行数据 } }
当前尝试的代码
for parameters_item in table_array: index = 0 # [[{'Type': '07BN4-AF'}, {'No.of Cores': '1'}, {'Section(mm²)': '1.5-630'}], [{'Type': '07BN4-AF'}, {'No.of Cores': '2、5'}, {'Section(mm²)': '1.0-240'}], [{'Type': '07BN4-AF'}, {'No.of Cores': '3-4'}, {'Section(mm²)': '1.0-300'}]] for row in parameters_item: # [{'Type': '07BN4-AF'}, {'No.of Cores': '1'}, {'Section(mm²)': '1.5-630'}] # [{'Type': '07BN4-AF'}, {'No.of Cores': '2、5'}, {'Section(mm²)': '1.0-240'}] # [{'Type': '07BN4-AF'}, {'No.of Cores': '3-4'}, {'Section(mm²)': '1.0-300'}] for row_index_item in row: parameters_inf = { 'row_index': { name[index]: row_index_item } } index += 1
解决方法
问题分析
- 原始
table_array存在多层嵌套、逗号缺失等语法错误,需先修正为统一的每行数据格式; - 原有代码未初始化结果容器,循环逻辑混乱,没有将每行的三个单键字典合并为完整的行数据。
正确实现代码
# 初始化结果模板 result = { 'parameters_row': 0, 'parameters_inf': {} } # 遍历每行数据,同时记录行索引 for row_idx, row_data in enumerate(table_array): # 合并当前行的三个单键字典为完整行字典 row_dict = {} for item in row_data: row_dict.update(item) # 将行字典存入parameters_inf,键为行索引的字符串 result['parameters_inf'][str(row_idx)] = row_dict # 更新总数据行数 result['parameters_row'] = len(result['parameters_inf']) # 打印验证结果(可选) import json print(json.dumps(result, indent=2, ensure_ascii=False))
代码说明
- 使用
enumerate遍历table_array,同时获取行索引和行数据; - 用
dict.update()方法将每行的三个单键字典合并为包含所有字段的完整字典; - 将合并后的行字典存入
parameters_inf,键采用行索引的字符串形式,匹配目标结构; - 最后更新
parameters_row为实际的总数据行数。
内容的提问来源于stack exchange,提问作者key
相关产品推荐
相关产品推荐

