2

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.

1
  • 1
    @JackMoody Please post this as an answer, not a comment. Commented Jan 25, 2019 at 22:29

2 Answers 2

2

The thing is, in add_medals_2 you are not updating the dictionary, you are update a copy you took from the dictionary.

Like this:

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
Sign up to request clarification or add additional context in comments.

2 Comments

I added print(test_dict) to show that it is never updated.
Thank you for your response, that makes sense to me.
1
silver_medals = test_dict['medals']['silver']

This copies the value on the left and assigns it to the name on the right.

silver_medals += 10

Now you assign the name on the left to a new value. This will not change the value in the dictionary because there is no knowledge of where the original value came from.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.