Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating a value in a tuple-value in nested dictionary in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading