このコードでエラーが発生しています
TypeError: 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)
ベストアンサー1
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