如何基于嵌套列表顺序在Python中填充预定义目标字典
用嵌套列表数据填充目标字典
给定源数据嵌套列表:
source = [['Ans1','Section1','Type2'],['Ans2','Section1','Type2'],['Ans3','Section2','Type2'],['Ans4','Section1','Type1']]
需要生成按最后一个元素(Type)分组的目标字典,结构如下:
{ "Type2":{ "0":{ "Ans":"Ans1", "Section":"Section1" }, "1":{ "Ans":"Ans2", "Section":"Section1" }, "2":{ "Ans":"Ans3", "Section":"Section2" }}, "Type1":{ "0":{ "Ans":"Ans4", "Section":"Section1" } }, "Type3":{}, "Type4":{}, "Type5":{} }
已通过以下代码创建好包含Type1-Type5的空目标字典api_res:
# Sorting my source data import operator source = [['Ans1','Section1','Type2'],['Ans2','Section1','Type2'],['Ans3','Section2','Type2'],['Ans4','Section1','Type1']] new_ = sorted(source, key = operator.itemgetter(0,2)) # Getting the count of Types doctype_list = [d[2] for d in new_] docs_count_dict = {} for x in set(doctype_list): docs_count_dict[x] = doctype_list.count(x) # Sorting the type based on new_ list sorted_docs = sorted(set(doctype_list),key=doctype_list.index) sorted_docs_orig = sorted_docs.copy() tot_types = ['Type1','Type2','Type3','Type4','Type5'] # Sorting the types out of total types for val in tot_types: if val in sorted_docs: continue sorted_docs.append(val) # Creating my empty target: api_res = {} for val in sorted_docs: api_res[val] = {} cols = ['Ans','Section'] for key,val in api_res.items(): if key in docs_count_dict: for i in range(docs_count_dict[key]): val[i] = dict.fromkeys(cols, "")
填充字典的实现代码
通过遍历排序后的源数据,为每个Type维护计数器,即可按顺序填充目标字典:
# 为每个Type初始化索引计数器 type_counters = {key: 0 for key in api_res.keys()} # 遍历排序后的源数据,填充对应字段 for item in new_: ans, section, type_key = item current_idx = type_counters[type_key] # 填入当前Type对应索引的子字典 api_res[type_key][current_idx]['Ans'] = ans api_res[type_key][current_idx]['Section'] = section # 更新计数器,准备填充下一条同Type数据 type_counters[type_key] += 1 # 格式化打印结果 import json print(json.dumps(api_res, indent=2))
代码说明
- 计数器初始化:为所有Type(包括无数据的Type3-Type5)创建计数器,确保每个Type下的条目按顺序填充。
- 数据遍历与填充:逐个取出排序后的源数据,拆分出
Ans、Section和Type键,通过计数器找到当前Type对应的子字典索引,填入数据。 - 计数器更新:每填充一条数据后,对应Type的计数器加1,保证下一条同Type数据填入下一个索引位置。
执行后,api_res将完全匹配目标字典格式。
内容的提问来源于stack exchange,提问作者usr_lal123
相关产品推荐
相关产品推荐

