279

このコードは私にエラーを与えています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)
4

2 に答える 2

367

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 が不変値のみで構成されている場合は、次のようにハッシュ可能な表現を作成できます。

>>> key = frozenset(dict_key.items())

またはkeyのキーとして使用できます。dictset

>>> 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それ自体が辞書やリストである値がある場合は、将来のキーを再帰的に「凍結」する必要があります。出発点は次のとおりです。

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
于 2012-11-07T07:03:52.613 に答える