fiacobelli
fiacobelli

Reputation: 1990

tuple as key to a dictionary says: 'tuple' object does not support item assignment

I have this function in python:

def initialize(s,cfg):
    pi={},
    for i,w in enumerate(s):
        j=i+1
        for X,rhs in cfg.items():
            if rhs.has_key(w):
                print (j,j,X),rhs[w]
                pi[(j,j,X)]=rhs[w]
    return pi

and when run I get

    pi[(j,j,X)]=rhs[w]
TypeError: 'tuple' object does not support item assignment

The print above it returns (1, 1, 'DT') 1.0

I must be missing something, but as far as I can see I am not trying to mutate the tuple. Why do I get that error?

At one point I thought that it may be due to j and X being pointed to and tried to create a new tuple, but that didn't work. I also tried this on the shell:

>>> pi={}
>>> X="DT"
>>> j=1
>>> t=(j,j,X)
>>> pi[t]=1.0
>>> pi
{(1, 1, 'DT'): 1.0}

and as you can see, it all works. Any ideas on why do I get the tuple does not support item assignment error in my function, but not on the shell?

Upvotes: 2

Views: 1210

Answers (1)

orlp
orlp

Reputation: 117661

You have a trailing comma on this line:

pi={},

Which is shorthand for:

pi = ({},)

In other words, pi is a tuple.

Upvotes: 5

Related Questions