How to update a dictionary value in python

Question:

I’ve created a dictionary with range :

answered = dict.fromkeys(range(1,51))

output:

{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None, 10: None, 11: None, 12: None, 13: None, 14: None, 15: None, 16: None, 17: None, 18: None, 19: None, 20: None, 21: None, 22: None, 23: None, 24: None, 25: None, 26: None, 27: None, 28: None, 29: None, 30: None, 31: None, 32: None, 33: None, 34: None, 35: None, 36: None, 37: None, 38: None, 39: None, 40: None, 41: None, 42: None, 43: None, 44: None, 45: None, 46: None, 47: None, 48: None, 49: None, 50: None}

and I’ve tried to update the values like this:

answered[1] = sent_answer #sent_answer -> some text

but what I get is:

{1: None, 2: None, 3: None, ..... ,49: None, 50: None, '1': 'I- III - II - IV'}

it’s adding a new dict item and the key is str so instead I want it to update the value of the specified key.

Asked By: M.Mevlevi

||

Answers:

Same thing as @NicolasGuruphat answer.

I believe the issue you have is one this part

and I’ve tried to update the values like this:

answered[1] = sent_answer #sent_answer -> some text```

I think if you went back to your code you’ll find answered["1"] instead of answered[1]

Answered By: unknown989

Make sure you have same type of the key you are trying to update. If it was a string in the dict, then when updating, use a string. If you do otherwise, python will see it as a different key and add one.

answers = {1: None, 2: None, 3: None}
answers[1] = 'some text'
print(answers)

Output:

{1: 'some text', 2: None, 3: None}

But if you use different type, then a new key is added.

answers['2'] = 'new text'
print(answers)

Output:

{1: 'some text', 2: None, 3: None, '2': 'new text'}

Keys are also case sensitive when they are string.

Answered By: Sakib Hasan

If you want to make sure it will do the job 100%, better use update method of the dictionary like below:

my_dict = {1:"a value", 2:"another value"}
my_dict.update({1:"your value"})

also, from Python 3.10 on you can do the following:

my_dict |= {1:"your value"}

still, there is more:

my_dict = {**my_dict, 1:"your value"}

and you will get the following result:

{1:"your value", 2:"another value"}

note that you can add the current key value or new ones. In general, it’s an upsert kind of operation.

Answered By: El.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.