Home > Software engineering >  Updating a value in a tuple-value in nested dictionary in python
Updating a value in a tuple-value in nested dictionary in python

Time:04-06

I have a following dictionary-

Diction = {'stars': {(4, 3): (2, 3, 100, 0), (3, 4): (3, 2)}}

I am trying to update a value as following:-

list(Diction['stars'][(4,3)])[-1] = 8765     #converting to list as tuples are immutable

After that I printed to verify, but value has not changed and it does not show any error.

print(list(Diction['stars'][(4,3)]))

Could anyone please let me know how can I update the value here?

CodePudding user response:

As you noted yourself, tuples are immutable. You cannot change their contents.

You can of course always just create a new tuple with the updated value and replace the old tuple with this one.

Something like

Diction = {'stars': {(4, 3): (2, 3, 100, 0), (3, 4): (3, 2)}}
temp = list(Diction['stars'][(4,3)]) 
temp[-1] = 8765
Diction['stars'][(4,3)] = tuple(temp) # convert back to a tuple

CodePudding user response:

When you cast your tuple to a list, you essentially make a copy of the tuple. If you still want to have the same functionality and keep the items as a tuple and not a list, you can do the following:

Diction = {'stars': {(4, 3): (2, 3, 100, 0), (3, 4): (3, 2)}}

my_item = list(Diction["stars"][4, 3])
my_item[-1] = 8765
Diction['stars'][4, 3] = tuple(my_item)

Here, we make the copy first, change it, then add the value back to the original as a tuple.

  • Related