TypeError: unhashable type: 'dict'
此错误表明您正在尝试使用字典作为字典中的键或设置。默认情况下,字典无法进行哈希处理,因此不能用作键。
解决方案:
要解决此问题,您可以使用 freezeset 冻结字典,它创建了字典的可哈希表示。不变性至关重要,因为只有不可变的对象(如字符串、数字和元组)才能被哈希。
示例:
考虑以下代码:
<code class="python">movie_reviews = ... negids = movie_reviews.fileids('neg') def word_feats(words): return dict([(word, True) for word in words]) # Constructing a list of tuples instead of dicts for hashability 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]) # Use frozenset to freeze the key (dict) of the nested dictionary result = {frozenset(key.items()): value for key, value in negfeats}</code>
在此示例中,negfeats 列表是使用元组而不是字典构建的,以确保可散列性。此外,stopword_filtered_word_feats 函数返回与原始代码不同的字典结构,其中键是冻结的元组集。该结构是可散列的并且与更新的代码兼容。
以上是以下是一些标题选项,重点关注核心问题和解决方案: 直接且信息丰富: * TypeError: \'unhashable type: \'dict\'\' - 如何在 Python 中使字典可哈希 * py的详细内容。更多信息请关注PHP中文网其他相关文章!