首页  >  文章  >  后端开发  >  以下是一些标题选项,重点关注核心问题和解决方案: 直接且信息丰富: * TypeError: \"unhashable type: \'dict\'\" - 如何在 Python 中使字典可哈希 * py

以下是一些标题选项,重点关注核心问题和解决方案: 直接且信息丰富: * TypeError: \"unhashable type: \'dict\'\" - 如何在 Python 中使字典可哈希 * py

DDD
DDD原创
2024-10-26 11:29:02132浏览

Here are a few title options, focusing on the core issue and solution:

Direct and Informative:

* TypeError:

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中文网其他相关文章!

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