首页  >  文章  >  后端开发  >  为什么使用字典作为集合中的键会引发“TypeError: unhashable type: \'dict\'\”错误?

为什么使用字典作为集合中的键会引发“TypeError: unhashable type: \'dict\'\”错误?

DDD
DDD原创
2024-10-27 00:36:03997浏览

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

TypeError: Unhashable Type: 'dict'

问题:

为什么以下代码会引发“TypeError: unhashable type: 'dict'" 错误?

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)

答案:

发生错误是因为您尝试使用字典作为创建的集合中的键通过 stopset 变量。但是,字典不是可哈希对象,这意味着它们不能用作集合或字典中的键。

解决方案:

要解决此问题,您可以将对冻结集合的否定功能中的字典是可散列的。以下代码显示了更正后的版本:

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)

以上是为什么使用字典作为集合中的键会引发“TypeError: unhashable type: \'dict\'\”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn