Problem:
Why does the following code raise a "TypeError: unhashable type: 'dict'" error?
negfeats = [(word_feats(movie_reviews.words(fileids=[f])), 'neg') for f in negids] stopset = set(stopwords.words('english')) def stopword_filtered_word_feats(words): return dict([(word, True) for word in words if word not in stopset]) result=stopword_filtered_word_feats(negfeats)
Answer:
The error occurs because you are attempting to use a dictionary as a key in the set created by the stopset variable. However, dictionaries are not hashable objects, which means they cannot be used as keys in sets or dictionaries.
Solution:
To resolve the issue, you can convert the dictionaries in negfeats to frozen sets, which are hashable. The following code shows the corrected version:
negfeats = [(frozenset(word_feats(movie_reviews.words(fileids=[f])).items()), 'neg') for f in negids] stopset = set(stopwords.words('english')) def stopword_filtered_word_feats(words): return dict([(word, True) for word in words if word not in stopset]) result=stopword_filtered_word_feats(negfeats)
The above is the detailed content of Why does using a dictionary as a key in a set raise a \'TypeError: unhashable type: \'dict\'\' error?. For more information, please follow other related articles on the PHP Chinese website!