IT이야기

TypeError: 해시가 불가능한 유형: 'dict'

cyworld 2022. 3. 8. 21:57
반응형

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)

A를 사용하려는 경우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'

받아쓰기를 키로 사용하려면 먼저 해시될 수 있는 것으로 변환해야 한다.키로 사용할 명령어가 불변의 값으로만 구성된 경우 다음과 같이 해시 가능한 표현을 만들 수 있다.

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

가능한 해결책은 JSON 덤프() 방법을 사용하는 것일 수 있으므로 사전을 문자열로 변환할 수 있다. --

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

참조URL: https://stackoverflow.com/questions/13264511/typeerror-unhashable-type-dict

반응형