gpt4 book ai didi

python - 类型错误 : unhashable type: 'dict'

转载 作者:IT老高 更新时间:2023-10-28 12:30:56 26 4
gpt4 key购买 nike

这段代码给我一个错误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 作为另一个 dictset 的键。这不起作用,因为 key 必须是可散列的。作为一般规则,只有不可变对象(immutable对象)(字符串、整数、 float 、卡住集、不可变元组)是可散列的(尽管可能有异常(exception))。所以这不起作用:

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

要将 dict 用作​​键,您需要先将其转换为可以被散列的东西。如果您希望用作键的 dict 仅包含不可变的值,您可以像这样创建它的可散列表示:

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

现在您可以使用 key 作为 dictset 中的键:

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

当然,当您想使用 dict 查找某些内容时,您需要重复该练习:

>>> 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

如果您希望用作键的 dict 具有本身是 dicts 和/或列表的值,您需要递归地“卡住”预期键。这是一个起点:

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

关于python - 类型错误 : unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13264511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com