I am relatively new to programming and am trying to better understand how to update values within dictionaries. A problem that I keep coming across is that when I set a dictionary's value to a variable and try to update it within a function, the value is not updated properly.
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
In the function add_medals_1, the value of 'bronze' is properly updated and increments each time the function is called. In the function add_medals_2, the value of 'silver' is not properly updated and does not increment. I am confused by this because both functions are similar but do not produce the output I expected.