Python使用for循环创建嵌套字典时内层键值被覆盖如何解决
问题修复方案
问题根因
- 每次遍历文件行时都会重新创建空的
inner_dict,并直接覆盖外层字典中对应组件类型的值,导致同分类下之前的记录全部丢失 - 内层
for i in range(1, len(parts))循环为冗余逻辑,无实际作用
修改逻辑
- 处理每行数据前先校验外层字典是否存在当前组件类型的键:不存在则先初始化空的内层字典,存在则直接复用已有内层字典
- 直接向内层字典追加当前行的硬件名称与价格,无需每次新建内层字典
- 替换变量名
type(Python内置函数,不建议作为变量名使用)为comp_type - 改用
with语句管理文件句柄,无需手动调用close()方法,更安全
修改后完整代码
def main(): filename = input("Enter the component file name: ") outer_dict = {} # 用with语句自动管理文件关闭 with open(filename, mode="r") as file: for row in file: row = row.strip() if not row: # 跳过空行 continue parts = row.split(";") comp_type = parts[0] name = parts[1] price = int(parts[2]) # 不存在当前分类时先初始化空内层字典 if comp_type not in outer_dict: outer_dict[comp_type] = {} # 直接往对应内层字典加键值对,不会覆盖之前的记录 outer_dict[comp_type][name] = price # 打印验证结果 print(outer_dict) if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者strawberrycheesecake
相关产品推荐
相关产品推荐

