首页  >  文章  >  后端开发  >  如何在 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