以下是一些標題選項,重點關注核心問題和解決方案: 直接且資訊豐富: * TypeError: \'unhashable type: \'dict\'\' - 如何在 Python 中使字典可哈希 * py

DDD
發布: 2024-10-26 11:29:02
原創
140 人瀏覽過

Here are a few title options, focusing on the core issue and solution:

Direct and Informative:

* TypeError:

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!