반응형
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
에서 키로 사용할 수 있습니다 .dict
set
>>> 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.dump(b)]
set(c)
json.dump(a) in c
출력-
set(['{"a": 10, "b": 20}'])
True
참고 URL : https://stackoverflow.com/questions/13264511/typeerror-unhashable-type-dict
반응형
'development' 카테고리의 다른 글
Visual Studio 2008 다운로드 및 설치 (0) | 2020.06.23 |
---|---|
HTML에서 작은 따옴표를 사용할 수 있습니까? (0) | 2020.06.23 |
루비를위한 최고의 / 쉬운 GUI 라이브러리는 무엇입니까? (0) | 2020.06.23 |
백그라운드 프로세스 포크 / 실행을위한 bash 앰퍼샌드 (&)와 동등한 Powershell (0) | 2020.06.23 |
"동결 된 dict"은 무엇입니까? (0) | 2020.06.23 |