如何在 Python 中使用字典作为键:解决'TypeError: unhashable type: \'dict\'\”错误

Mary-Kate Olsen
发布: 2024-10-27 02:25:30
原创
367 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!