首頁  >  文章  >  後端開發  >  如何在 Python 中使用字典作為鍵:解決“TypeError: unhashable type: \'dict\'\”錯誤

如何在 Python 中使用字典作為鍵:解決“TypeError: unhashable type: \'dict\'\”錯誤

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-27 02:25:30354瀏覽

How to Use Dictionaries as Keys in Python: Resolving the

TypeError: unhashable type: 'dict'

當遇到錯誤訊息「TypeError: unhashable type: 'dict'」時,表示您正在嘗試使用字典作為另一個字典或集合中的鍵。這是不允許的,因為鍵必須具有雜湊性,而雜湊性通常僅由不可變物件(字串、數字、不可變元素的元組、凍結集等)支援。

要使用字典作為鍵,您需要將其轉換為可雜湊表示。如果字典僅包含不可變值,您可以透過將其凍結為不可變資料結構來實現此目的:

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

現在,您可以使用'key' 作為其他字典或集合中的鍵:

<code class="python">some_dict[key] = True</code>

請記住,每當您想要使用字典存取資料時,您都需要始終使用凍結表示:

<code class="python">some_dict[dict_key]  # This will raise an error
some_dict[frozenset(dict_key.items())]  # This works</code>

如果字典的值本身就是字典或列表,則您可以需要採用遞歸凍結來確保可雜湊性:

<code class="python">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</code>

透過利用此功能,您可以凍結字典並將其用作可雜湊結構中的鍵:

<code class="python">frozen_dict = freeze(dict_key)
some_dict[frozen_dict] = True</code>

以上是如何在 Python 中使用字典作為鍵:解決“TypeError: unhashable type: \'dict\'\”錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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