Python生成嵌套字典时循环追加列表值被覆盖的问题求助
问题:生成嵌套字典时值被覆盖,仅保留最后一项
尝试通过邮编与位置列表生成嵌套字典,但循环过程中值不断被覆盖,最终列表仅保留最后一个值。
问题代码片段
postcode_dict = {} postcode_list = [['01000', 'location1', 'district1', 'state1'], ['01000', 'location2', 'district1', 'state1'], ['01200', 'location3', 'district2', 'state2'], ['01200', 'location4', 'district2', 'state2']] for row in postcode_list: state = row[3] state_dict = {} if state not in state_dict: district_loc = [] temp = [{row[1]: row[0]}] district_loc.append(temp) state_dict[row[2]] = district_loc postcode_dict[row[3]] = {district: district_loc} print(postcode_dict)
实际输出结果
{'state1': {'district1': [{'location2': '01000'}]}, 'state2': {'district2': [{'location4': '01200'}]}}
预期输出结果
{'state1': {'district1': [{'location1': '01000'}, {'location2': '01000'}]}, 'state2': {'district2': [{'location3': '01200'}, {'location4': '01200'}]}}
问题原因分析
- 循环内重置字典:
state_dict = {}在每次循环中初始化,导致之前累积的state数据被清空,无法保留同一state下的多个district信息 - 无效的存在性判断:
if state not in state_dict完全无效,因为刚创建的state_dict是空字典,该条件永远为真 - 直接覆盖状态数据:
postcode_dict[row[3]] = {district: district_loc}每次都会给对应state赋值新字典,直接覆盖之前的结果 - 无法累积位置数据:
district_loc每次循环重新创建,无法收集同一district下的多个位置条目
修正后的代码
postcode_dict = {} postcode_list = [['01000', 'location1', 'district1', 'state1'], ['01000', 'location2', 'district1', 'state1'], ['01200', 'location3', 'district2', 'state2'], ['01200', 'location4', 'district2', 'state2']] for row in postcode_list: postcode, location, district, state = row # 确保当前state在总字典中存在对应的子字典 if state not in postcode_dict: postcode_dict[state] = {} # 获取当前state对应的子字典 state_data = postcode_dict[state] # 确保当前district在state子字典中存在对应的列表 if district not in state_data: state_data[district] = [] # 将当前位置数据添加到对应district的列表中 state_data[district].append({location: postcode}) print(postcode_dict)
修正思路说明
- 先检查并创建层级结构:从state到district,确保每个层级的容器(字典/列表)已存在,避免每次循环重置结构
- 直接向已存在的列表中追加新的位置数据,实现数据累积,而非每次覆盖整个结构
内容的提问来源于stack exchange,提问作者Cryssie
相关产品推荐
相关产品推荐

