类型错误:不可散列的类型:'dict'

2024-02-19

这段代码给了我一个错误

TypeError: unhashable type: dict

谁能向我解释一下解决方案是什么?

negids = movie_reviews.fileids('neg')
def word_feats(words):
    return dict([(word, True) for word in words])

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)

您正在尝试使用dict作为另一把钥匙dict或在一个set。这是行不通的,因为密钥必须是可散列的。作为一般规则,只有不可变对象(字符串、整数、浮点数、冻结集、不可变元组)是可哈希的(尽管也可能有例外)。所以这不起作用:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

要使用字典作为键,您需要将其转换为可以首先进行哈希处理的内容。如果您希望用作键的字典仅包含不可变值,您可以创建它的可哈希表示,如下所示:

>>> key = frozenset(dict_key.items())

现在你可以使用key作为一个关键dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

当然,每当你想使用字典查找某些内容时,你都需要重复这个练习:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict您希望使用的键值本身就是字典和/或列表,您需要递归地“冻结”预期键。这是一个起点:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型错误:不可散列的类型:'dict' 的相关文章

随机推荐