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

Python中while True循环覆盖二维字典所有键值的问题求助

问题解析:循环中字典赋值导致所有键值被覆盖的原因

核心原因:字典是可变对象,赋值传递的是引用

Python里的字典属于可变对象,当你执行MokeDex[name] = MokeBeast时,并没有把MokeBeast里的内容复制一份存到MokeDex里,而是把这个字典的内存引用存了进去。

你的代码执行流程问题

  • 你在循环外只创建了一个MokeBeast字典对象
  • 每次while循环里,你只是修改这个同一个对象的键值对
  • MokeDex里所有的键指向的都是这个唯一的字典引用,所以每次修改MokeBeast时,所有键对应的“值”都会同步更新,看起来就像是所有旧键的值被新内容覆盖了

为什么第二种写法正常?

你后来用的mokedex[name] = { "type": type, "hp": hp, "mp": mp}能正常工作,是因为每次循环都会创建一个全新的字典对象,MokeDex里的每个键都指向独立的新字典,它们之间互不干扰。

修复原代码的两种方法

方法1:每次循环内创建新的字典对象

把MokeBeast的定义放到while循环内部,确保每次添加新怪物时都生成一个全新的字典:

MokeDex = {}

while True:
  name = input("Input your beast's name >")
  # 每次循环创建新的字典模板
  MokeBeast = {"type": None, "specialmove": None, "startingHP": None, "startingMP": None}
  for key in MokeBeast.keys():
    MokeBeast[key] = input(f"Input your beast's {key} >")

  MokeDex[name] = MokeBeast
  check = input("Do you want to add another beast? y/n>")
  if check == "n":
    break

方法2:存储字典的副本而非原引用

使用copy()方法复制当前MokeBeast的内容,生成一个新字典存入MokeDex:

MokeDex = {}
MokeBeast = {"type": None, "specialmove": None, "startingHP": None, "startingMP": None}

while True:
  name = input("Input your beast's name >")
  for key in MokeBeast.keys():
    MokeBeast[key] = input(f"Input your beast's {key} >")

  # 存入当前字典的副本,避免引用同一对象
  MokeDex[name] = MokeBeast.copy()
  check = input("Do you want to add another beast? y/n>")
  if check == "n":
    break

内容的提问来源于stack exchange,提问作者user2566834

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:15:14