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

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

问题描述

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:


  1. 一对元组。你已经在你的问题上做到了。 tuple 是必需的,而不是 list ,因为结果依赖于元素的不变性。

  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 an immutability of the elements.

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


  • 从数学的角度来看,这是一个比较合适的方法,因为它只需要 c 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屋!

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