为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

料青山看我应如是 2019-11-30 14:16:14
这段代码给我一个错误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)
查看完整描述

3 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

您正在尝试将a dict用作另一个dict或a 中的键set。那是行不通的,因为密钥必须是可哈希的。通常,只有不可变的对象(字符串,整数,浮点数,frozensets,不可变的元组)才是可哈希化的(尽管可能有例外)。因此,这不起作用:


>>> 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或中用作键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

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


查看完整回答
反对 回复 2019-11-30
?
温温酱

TA贡献1752条经验 获得超4个赞

可能的解决方案可能是使用JSON dumps()方法,因此您可以将字典转换为字符串-


import json

a={"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


查看完整回答
反对 回复 2019-11-30
  • 3 回答
  • 0 关注
  • 1128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号