+2 votes
in Programming Languages by (17.2k points)
I have a Python dictionary like this "aa={0.5:(0,0)}" where the value is a tuple. I want to increase the value of one element of the tuple depending on some condition, but I am getting error "TypeError: 'tuple' object does not support item assignment". How to fix this error?

1 Answer

0 votes
by (30.2k points)

As the error says, you should not use tuple as value. You can do one of the followings:

1. Change the value from tuple to a list and then your operation will work.

>>> aa={0.5:[0,0],0.10:[0,0]}
>>> aa[0.5][0]+=1
>>> aa
{0.5: [1, 0], 0.1: [0, 0]}

2. Long process

>>> aa={0.5:(0,0),0.10:(0,0)}
>>> aa[0.5]=list(aa[0.5])    #convert to list (mutable)
>>> aa[0.5][0]+=1    #do your operation
>>> aa[0.5]=tuple(aa[0.5])    #convert back to tuple (immutable)
>>> aa
{0.5: (1, 0), 0.1: (0, 0)}