반응형
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
반응형
'IT이야기' 카테고리의 다른 글
VueJS 조건부로 요소의 속성 추가 (0) | 2022.03.08 |
---|---|
반응식 런오스가 시뮬레이터를 찾을 수 없음 (0) | 2022.03.08 |
vue-cli 프로젝트에서 포트 번호를 변경하는 방법 (0) | 2022.03.08 |
파이썬에서 scp 하는 법? (0) | 2022.03.08 |
Vue-cli 버전 3 베타 웹 팩 구성 (0) | 2022.03.08 |