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

为什么Python字典的值不会随外部已赋值变量的更新而变化?

遗漏的核心知识点

Python中的字符串属于不可变数据类型,你将变量赋值给字典的值时,实际是将变量当前指向的字符串值复制存入字典,而非存储变量本身的引用。后续你对原变量重新赋值,只是让变量指向了新的字符串对象,字典中存储的旧字符串值不会随之更新,所以才会出现两次打印结果一致的情况。

实现预期效果的方案
  • 方案1:手动同步更新字典对应键的值
    这是最常用、最简单的方案,修改变量后同步更新字典对应的键值即可:
firstValue = "First Value Key"
secondValue = "Second Value Key"
thirdValue = "Third Value Key"

Dictionary = {"0":firstValue,
              "1":secondValue,
              "2":thirdValue}

print(Dictionary["0"])

firstValue = "New Value"
Dictionary["0"] = firstValue # 新增这行同步字典值

print(Dictionary["0"])
  • 方案2:存储可变对象实现自动同步
    如果不想每次手动更新字典,可以将值存在列表这类可变对象中,字典存储的是可变对象的引用,修改对象内容时字典会自动同步:
# 变量改为存储单元素列表(可变对象)
firstValue = ["First Value Key"]
secondValue = ["Second Value Key"]
thirdValue = ["Third Value Key"]

Dictionary = {"0":firstValue,
              "1":secondValue,
              "2":thirdValue}

print(Dictionary["0"][0])

# 修改列表的元素值,无需修改字典
firstValue[0] = "New Value"

print(Dictionary["0"][0])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:54:06