python - 通过变量修改嵌套字典
问题描述
我对编程比较陌生,并且正在尝试更好地了解如何更新字典中的值。我经常遇到的一个问题是,当我将字典的值设置为变量并尝试在函数中更新它时,该值没有正确更新。
test_dict = {
'medals': {
'bronze': 0,
'silver': 0,
'gold': 0,
},
}
def add_medals_1(test_dict):
test_dict['medals']['bronze'] += 10
print(test_dict['medals']['bronze'])
add_medals_1(test_dict) # Updates value of bronze to 10
add_medals_1(test_dict) # Updates value of bronze to 20
def add_medals_2(test_dict):
silver_medals = test_dict['medals']['silver']
silver_medals += 10
print(silver_medals)
add_medals_2(test_dict) # Updates value of silver to 10
add_medals_2(test_dict) # Value of silver remains at 10
在函数 add_medals_1 中,“青铜”的值会在每次调用该函数时正确更新并递增。在函数 add_medals_2 中,'silver' 的值没有正确更新并且不会增加。我对此感到困惑,因为这两个功能相似,但不会产生我预期的输出。
解决方案
问题是,在add_medals_2
您没有更新字典时,您正在更新从字典中获取的副本。
像这样:
def add_medals_2(test_dict):
# 1) HERE, you are copying test_dict['medals']['silver']
# to another memory location (variable) called silver_medals
silver_medals = test_dict['medals']['silver']
# 2) THEN, you update variable's value to += 10
silver_medals += 10
# You print the updated value
print(test_dict)
print(silver_medals)
# BUT, test_dict was never updated in add_medals_2
推荐阅读
- laravel - Laravel 查询生成器/如何阻止它添加方 [括号]?
- android - javax.net.ssl.SSLHandshakeException 在 android 9.0 和 8.0 中显示带有 glide 的图像时出现,但在 android 6.0 和 10 中运行良好
- android - findNavController 使用上下文
- java - 使用 ThreadLocal.get() 获取不确定值
- jquery - 调用/显示html元素时如何从数据库中加载值
- vue.js - 将数据从组件发送到组件
- css - 使 div 容器调整为 svg 高度
- c++ - CUDA C++ 从主机读取图像并复制到设备
- c# - 更改项目以使用 DI 后的 EF Core 迁移
- reactjs - 即浏览器 iframe 有 src 源但 body 和 head 是空的