背景
由于需要,要从Excel文件中生成一个多级结构的字典,其中层级以'$'符来进行区分,现在将代码粘贴如下
def generate_nested_dict(final_dict, key_name, value):
key_list = key_name.split(r'$')
curr_data = final_dict
for i in key_list[:-1]:
if i in curr_data.keys():
curr_data = curr_data[i]
else:
curr_data[i] = {}
curr_data = curr_data[i]
curr_data[key_list[-1]] = value
# 生成unit_config
def generate_unit_config(xl_workbook):
sheet_names = xl_workbook.sheet_names()
xl_sheet = xl_workbook.sheet_by_name(sheet_names[0])
col_names = [cell_obj.value for cell_obj in xl_sheet.row(0)]
key_names = xl_sheet.col_values(col_names.index('key'), 1)
values = xl_sheet.col_values(col_names.index('数值'), 1)
values = list(map(str, values))
final_dict = dict()
for idx, (key_name, value) in enumerate(zip(key_names, values)):
if value.find('[') != -1 and value.find(']') != -1:
value = value[1:-1].split(',')
generate_nested_dict(final_dict, key_name, value)
return final_dict
参考
参考的这篇,逻辑真的让我瑞思拜。Link