TypeError: unhashable type: 'dict'
此錯誤表明您正在嘗試使用字典作為字典中的鍵或設定。預設情況下,字典無法進行雜湊處理,因此不能用作鍵。
解決方案:
要解決此問題,您可以使用 freezeset 凍結字典,它創建了字典的可哈希表示。不變性至關重要,因為只有不可變的物件(如字串、數字和元組)才能被雜湊。
範例:
考慮以下程式碼:
<code class="python">movie_reviews = ... negids = movie_reviews.fileids('neg') def word_feats(words): return dict([(word, True) for word in words]) # Constructing a list of tuples instead of dicts for hashability 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]) # Use frozenset to freeze the key (dict) of the nested dictionary result = {frozenset(key.items()): value for key, value in negfeats}</code>
在此範例中,negfeats 清單是使用元組而不是字典建構的,以確保可散列性。此外,stopword_filtered_word_feats 函數會傳回與原始程式碼不同的字典結構,其中鍵是凍結的元組集。該結構是可散列的並且與更新的程式碼相容。
以上是以下是一些標題選項,重點關注核心問題和解決方案: 直接且資訊豐富: * TypeError: \"unhashable type: \'dict\'\" - 如何在 Python 中使字典可哈希 * py的詳細內容。更多資訊請關注PHP中文網其他相關文章!