Invalid syntax in Python’s for statement

I am trying to run the code below, and when I run python (Python 2.6.9) I get SyntaxError: invalid syntax error in the line below, pointing to the for statement. What am I doing wrong?

def produceVector(blob, bloblist):
    ##### SYNTAXERROR: invalid syntax in the "for" in the line below #####
    scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
    return scores

def tf(word, blob):
    return blob.words.count(word) / len(blob.words)

def n_containing(word, bloblist):
    return sum(1 for blob in bloblist if word in blob)

def idf(word, bloblist):
    return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
    return tf(word, blob) * idf(word, bloblist)


That’s not a for statement, that’s a dict comprehension. Which was only introduced in 2.7. Generate an iterable of 2-tuples instead and pass it to the dict() constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *