TypeError:无法散列的类型:'dict'

这段代码给我一个错误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)


料青山看我应如是
浏览 1129回答 3
3回答

犯罪嫌疑人X

您正在尝试将a dict用作另一个dict或a 中的键set。那是行不通的,因为密钥必须是可哈希的。通常,只有不可变的对象(字符串,整数,浮点数,frozensets,不可变的元组)才是可哈希化的(尽管可能有例外)。因此,这不起作用:>>> dict_key = {"a": "b"}>>> some_dict[dict_key] = TrueTraceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: unhashable type: 'dict'要将字典用作键,您需要将其转换为可能首先进行哈希处理的东西。如果要用作键的字典仅由不可变值组成,则可以像这样创建可散列的表示形式:>>> key = frozenset(dict_key.items())现在,您可以key在dict或中用作键set:>>> some_dict[key] = True>>> some_dict{frozenset([('a', 'b')]): True}当然,每当要使用字典查找某些内容时,都需要重复练习:>>> some_dict[dict_key]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# Doesn't workTraceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: unhashable type: 'dict'>>> some_dict[frozenset(dict_key.items())]&nbsp; # WorksTrue如果dict您希望用作键的值本身就是字典和/或列表,则需要递归“冻结”预期键。这是一个起点:def freeze(d):&nbsp; &nbsp; if isinstance(d, dict):&nbsp; &nbsp; &nbsp; &nbsp; return frozenset((key, freeze(value)) for key, value in d.items())&nbsp; &nbsp; elif isinstance(d, list):&nbsp; &nbsp; &nbsp; &nbsp; return tuple(freeze(value) for value in d)&nbsp; &nbsp; return d

温温酱

可能的解决方案可能是使用JSON dumps()方法,因此您可以将字典转换为字符串-import jsona={"a":10, "b":20}b={"b":20, "a":10}c = [json.dumps(a), json.dump(b)]set(c)json.dump(a) in c输出-set(['{"a": 10, "b": 20}'])True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python