TypeError:不可用类型:'dict'

use*_*250 144 python

这段代码给我一个错误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)
Run Code Online (Sandbox Code Playgroud)

Lau*_*low 213

你正在尝试使用a dict作为另一个dict或一个的关键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'
Run Code Online (Sandbox Code Playgroud)

要使用dict作为键,您需要将其转换为可能首先进行哈希处理的内容.如果您希望用作键的dict只包含不可变值,则可以像这样创建一个hashable表示:

>>> key = frozenset(dict_key.items())
Run Code Online (Sandbox Code Playgroud)

现在你可以key用作a dict或中的键set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
Run Code Online (Sandbox Code Playgroud)

当然,只要你想用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
Run Code Online (Sandbox Code Playgroud)

如果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
Run Code Online (Sandbox Code Playgroud)

  • 只是注意@StevenDu字典不保证顺序,所以`str(my_dict)`可以返回两个不同的字符串,用于相同(或不同但等效)的字符串 (7认同)
  • 在我看来,“frozenset(dict_key.items())”可能存在问题,因为两个具有相同内容但插入顺序不同的字典可能不会产生相同的密钥。添加对排序()的调用似乎是正确的。例如 `frozenset(sorted(dict_key.items()))` 此外,鉴于集合是显式无序的,frozenset 似乎是一个奇怪的选择。它在实践中可能工作得很好,但元组对我来说似乎是一个更合理的选择。我选择了 `tuple(sorted(dict_key.items()))` (5认同)
  • 谢谢,它工作,但如果值是一个字典或列表(不可用)仍然会得到错误,现在我使用哈希(str(my_dict)),对我来说工作正常. (2认同)
  • 要将生成的 freezeset 转换回 dict,只需调用 dict(the_frozenset) 即可。 (2认同)

小智 16

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

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c
Run Code Online (Sandbox Code Playgroud)

输出 -

set(['{"a": 10, "b": 20}'])
True
Run Code Online (Sandbox Code Playgroud)

  • JSON 由[“一组无序的名称/值对”](https://www.json.org/json-en.html) 组成。因此,更改名称/值对的顺序将导致“不同”的 JSON 字符串,该字符串将被注册为该集合的新成员。实际上,这可能不是什么大问题,因为“json.dumps()”很可能是可预测的,但这是需要注意的。 (12认同)

Nat*_*ent 6

这发生在我身上,因为我正在用 Typescript 思考,并尝试像这样设置一个 python 字典:

thing = { 'key': 'value' }
other_thing = {'other_key': 'other_value'}
my_dictionary = { thing, other_thing }
Run Code Online (Sandbox Code Playgroud)

然后我尝试:

my_dictionary = { thing: thing, other_thing: other_thing }
Run Code Online (Sandbox Code Playgroud)

...这仍然不起作用

最终起作用的是......

my_dictionary = { 'thing': thing, 'other_thing': other_thing }
Run Code Online (Sandbox Code Playgroud)

有趣的是,我们如何习惯不同语言的小语法技巧......