首頁  >  文章  >  後端開發  >  為什麼 Python 會拋出 `TypeError: Unhashable Type \'dict\'` 以及如何修復它?

為什麼 Python 會拋出 `TypeError: Unhashable Type \'dict\'` 以及如何修復它?

Patricia Arquette
Patricia Arquette原創
2024-10-28 03:19:01954瀏覽

Why Does Python Throw a `TypeError: Unhashable Type 'dict'` and How to Fix It?

TypeError: Unhashable Type 'dict'

在Python 中,某些物件(例如字典)不能用作字典或集合中的鍵,因為它們不可散列。 Hashable 物件具有常數值,可用作從字典或集合中快速檢索資料的鍵。

要解決此錯誤,您需要將有問題的字典 (dict_key) 轉換為可哈希物件。實現此目的的一種方法是從字典的項目中建立一個 freezeset。

<code class="python">key = frozenset(dict_key.items())</code>

此freezeset 現在可以用作字典或集合中的鍵:

<code class="python">if key in some_dict:
    print("Key exists in the dictionary")</code>

請注意如果字典值本身包含其他不可散列的對象,則可能需要遞歸應用此凍結過程。

以上是為什麼 Python 會拋出 `TypeError: Unhashable Type \'dict\'` 以及如何修復它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn