Home > Software engineering >  How to update a dictionary value in python
How to update a dictionary value in python

Time:04-10

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.

CodePudding user response:

If you want to make sure it would 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"})

and you will get

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

note that you can add the existing key-values or new ones. In general, it's an upsert kind of operation.

CodePudding user response:

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]

CodePudding user response:

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.

  • Related