Why does using a dictionary as a key in a set raise a \'TypeError: unhashable type: \'dict\'\' error?

DDD
Release: 2024-10-27 00:36:03
Original
1084 people have browsed it

Why does using a dictionary as a key in a set raise a

TypeError: Unhashable Type: 'dict'

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template