使用 Python 字典作为键(非嵌套) [英] Using a Python Dictionary as a Key (Non-nested)

查看:40
本文介绍了使用 Python 字典作为键(非嵌套)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 不允许将字典用作其他字典中的键.是否有使用非嵌套字典作为键的解决方法?

更复杂的不可散列对象的一般问题和我的具体用例是 移至此处.我对用例的原始描述不正确.

解决方案

如果你有一个真正不可变的字典(虽然我不清楚你为什么不只使用对列表:例如 [('content-type', 'text/plain'), ('host', 'example.com')]),然后你可以将你的 dict 转换成:

  1. 一对元组.你已经在你的问题中做到了.需要一个 tuple 而不是 list 因为结果依赖于元素的顺序和不变性.

    <预><代码>>>>元组(排序(a.items()))

  2. 冻结集.从数学的角度来看,这是一种更合适的方法,因为它只需要对不可变 dict 元素的等式关系,而第一种方法需要排序关系除了平等.

    <预><代码>>>>冻结集(a.items())

Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys?

The general problem with more complicated non-hashable objects and my specific use case has been moved here. My original description of my use case was incorrect.

解决方案

If you have a really immutable dictionary (although it isn't clear to me why you don't just use a list of pairs: e.g. [('content-type', 'text/plain'), ('host', 'example.com')]), then you may convert your dict into:

  1. A tuple of pairs. You've already done that in your question. A tuple is required instead of list because the results rely on the ordering and the immutability of the elements.

    >>> tuple(sorted(a.items()))
    

  2. A frozen set. It is a more suitable approach from the mathematical point of view, as it requires only the equality relation on the elements of your immutable dict, while the first approach requires the ordering relation besides equality.

    >>> frozenset(a.items())
    

这篇关于使用 Python 字典作为键(非嵌套)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆