如何通过for循环创建多层嵌套字典?解决仅保留首个元素问题
问题:生成指定结构的多层嵌套字典
需求目标
需要生成如下结构的多层嵌套字典(注:字典键不可重复,实际实现中需用列表或带编号的键存储同日期的多个activity):
{ "in the kitchen": { "2010-01-05": {"activity": "...", "activity": "...", "activity": "..."}, "2010-01-06": {"activity": "...", "activity": "..."} } }
输入数据
my_list = [ ['2010-01-05 12:32:05', 'in the kitchen', 'ON'], ['2010-01-05 12:32:08', 'in the kitchen', 'ON'], ['2010-01-05 12:32:10', 'in the kitchen', 'ON'], ['2010-01-06 02:32:11', 'in the kitchen', 'ON'], ['2010-01-06 02:32:20', 'in the kitchen', 'ON'] ]
错误代码及问题
尝试以下代码后,输出仅保留首个元素,未保留同日期的其他activity及次日数据:
my_Dict= {} for i, item in enumerate(my_list): # calculating for every item the info i want to put in my dict res = str(time) # 假设此处已正确计算得到activity内容 p = item[0].split() # 提取日期部分 if item[1] not in my_Dict.keys(): my_Dict[item[1]] = dict() if item[0] not in my_Dict.keys(): my_Dict[item[1]][p[0]] = dict() my_Dict[item[1]][p[0]]["activity"] = res
错误输出:
{'in the kitchen': {'2010-01-05': {'activity': '...'}}}
错误原因分析
- 条件判断逻辑错误:检查日期是否存在时,错误判断
item[0]是否在my_Dict的键中,实际应检查提取出的日期p[0]是否在my_Dict[item[1]]的键中。 - 字典键覆盖问题:直接赋值
["activity"] = res会覆盖之前的值,且字典不允许重复键,无法存储多个activity记录。 - 缩进错误:内层
if语句缩进不正确,导致只有首次创建位置字典时才会赋值,后续循环无法执行。
正确代码实现
方案1:用列表存储同日期的activity(推荐,符合字典键唯一性规则)
my_Dict = {} for item in my_list: # 替换为你实际计算得到的activity内容,示例用时间字符串代替 res = item[0] location = item[1] date = item[0].split()[0] # 提取日期部分 # 初始化位置层级 if location not in my_Dict: my_Dict[location] = {} # 初始化日期层级,用列表存储多个activity if date not in my_Dict[location]: my_Dict[location][date] = {"activities": []} # 添加当前activity到列表 my_Dict[location][date]["activities"].append(res) # 输出结果 print(my_Dict)
输出结果:
{ 'in the kitchen': { '2010-01-05': {'activities': ['2010-01-05 12:32:05', '2010-01-05 12:32:08', '2010-01-05 12:32:10']}, '2010-01-06': {'activities': ['2010-01-06 02:32:11', '2010-01-06 02:32:20']} } }
方案2:用带编号的键存储同日期的activity(贴近需求写法)
my_Dict = {} for item in my_list: # 替换为你实际计算得到的activity内容,示例用时间字符串代替 res = item[0] location = item[1] date = item[0].split()[0] # 初始化位置层级 if location not in my_Dict: my_Dict[location] = {} # 初始化日期层级 if date not in my_Dict[location]: my_Dict[location][date] = {} # 生成带编号的activity键 activity_count = len(my_Dict[location][date]) + 1 my_Dict[location][date][f"activity_{activity_count}"] = res # 输出结果 print(my_Dict)
输出结果:
{ 'in the kitchen': { '2010-01-05': { 'activity_1': '2010-01-05 12:32:05', 'activity_2': '2010-01-05 12:32:08', 'activity_3': '2010-01-05 12:32:10' }, '2010-01-06': { 'activity_1': '2010-01-06 02:32:11', 'activity_2': '2010-01-06 02:32:20' } } }
内容的提问来源于stack exchange,提问作者Labarbona Dibaggio
相关产品推荐
相关产品推荐

