>  기사  >  백엔드 개발  >  사전을 세트의 키로 사용하면 \"TypeError: unhashable type: \'dict\'\" 오류가 발생하는 이유는 무엇입니까?

사전을 세트의 키로 사용하면 \"TypeError: unhashable type: \'dict\'\" 오류가 발생하는 이유는 무엇입니까?

DDD
DDD원래의
2024-10-27 00:36:03997검색

Why does using a dictionary as a key in a set raise a

TypeError: Unhashable Type: 'dict'

문제:

다음 코드에서 "TypeError: 해시할 수 없는 유형: 'dict'" 오류?

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)

답변:

생성된 세트에서 사전을 키로 사용하려고 하기 때문에 오류가 발생합니다. stopset 변수로. 그러나 사전은 해시 가능한 객체가 아니므로 세트나 사전에서 키로 사용할 수 없습니다.

해결책:

문제를 해결하려면 Negfeats의 사전을 해시 가능한 고정 세트로 변환합니다. 다음 코드는 수정된 버전을 보여줍니다.

negfeats = [(frozenset(word_feats(movie_reviews.words(fileids=[f])).items()), '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)

위 내용은 사전을 세트의 키로 사용하면 \"TypeError: unhashable type: \'dict\'\" 오류가 발생하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.