使用Python字典作为键(非嵌套) [英] Using a Python Dictionary as a Key (Non-nested)
问题描述
Python不允许在其他字典中使用字典作为键。有没有使用非嵌套字典作为键的解决方法?
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.
推荐答案
如果你有一个非常不可变的字典(尽管不清楚我为什么你不只是使用一个对的列表:例如 [('content-type','text / plain'),('host','example.com')]
),那么您可以将 dict
转换为:
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:
-
一对元组。你已经在你的问题上做到了。
tuple
是必需的,而不是list
,因为结果依赖于元素的不变性。
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 an immutability of the elements.
>>> tuple(sorted(a.items()))
从数学的角度来看,这是一个比较合适的方法,因为它只需要 c
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屋!