[python] 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)



답변

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'

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


답변

가능한 해결책은 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

출력-

set(['{"a": 10, "b": 20}'])
True


답변