首页 > 解决方案 > 通过变量修改嵌套字典

问题描述

我对编程比较陌生,并且正在尝试更好地了解如何更新字典中的值。我经常遇到的一个问题是,当我将字典的值设置为变量并尝试在函数中更新它时,该值没有正确更新。

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' 的值没有正确更新并且不会增加。我对此感到困惑,因为这两个功能相似,但不会产生我预期的输出。

标签: pythondictionary

解决方案


问题是,在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

推荐阅读