You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用for循环创建嵌套字典时内层键值被覆盖如何解决

问题修复方案

问题根因

  • 每次遍历文件行时都会重新创建空的inner_dict,并直接覆盖外层字典中对应组件类型的值,导致同分类下之前的记录全部丢失
  • 内层for i in range(1, len(parts))循环为冗余逻辑,无实际作用

修改逻辑

  1. 处理每行数据前先校验外层字典是否存在当前组件类型的键:不存在则先初始化空的内层字典,存在则直接复用已有内层字典
  2. 直接向内层字典追加当前行的硬件名称与价格,无需每次新建内层字典
  3. 替换变量名type(Python内置函数,不建议作为变量名使用)为comp_type
  4. 改用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:54:02