使用 Python 字典作为键(非嵌套) [英] Using a Python Dictionary as a Key (Non-nested)
问题描述
Python 不允许将字典用作其他字典中的键.是否有使用非嵌套字典作为键的解决方法?
更复杂的不可散列对象的一般问题和我的具体用例是 移至此处.我对用例的原始描述不正确.
如果你有一个真正不可变的字典(虽然我不清楚你为什么不只使用对列表:例如 [('content-type', 'text/plain'), ('host', 'example.com')]
),然后你可以将你的 dict
转换成:
一对元组.你已经在你的问题中做到了.需要一个
<预><代码>>>>元组(排序(a.items()))tuple
而不是list
因为结果依赖于元素的顺序和不变性.冻结集.从数学的角度来看,这是一种更合适的方法,因为它只需要对不可变
<预><代码>>>>冻结集(a.items())dict
元素的等式关系,而第一种方法需要排序关系除了平等.
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:
A tuple of pairs. You've already done that in your question. A
tuple
is required instead oflist
because the results rely on the ordering and the immutability of the elements.>>> tuple(sorted(a.items()))
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屋!