为什么我不能在python中使用列表作为dict键? [英] Why can't I use a list as a dict key in python?

查看:179
本文介绍了为什么我不能在python中使用列表作为dict键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,可以/不能用作python dict的关键。

I'm a bit confused about what can/can't be used as a key for a python dict.

dicked = {}
dicked[None] = 'foo'     # None ok
dicked[(1,3)] = 'baz'    # tuple ok
import sys
dicked[sys] = 'bar'      # wow, even a module is ok !
dicked[(1,[3])] = 'qux'  # oops, not allowed

所以一个元组是一个不变的类型,但是如果我隐藏了一个列表,那么它不能是一个关键..我不能像在一个模块中一样容易地隐藏列表

So a tuple is an immutable type but if I hide a list inside of it, then it can't be a key.. couldn't I just as easily hide a list inside a module?

我有一些含糊的想法,认为这个关键是哈希,但我只是承认自己对技术细节的无知;我不知道这里真的发生了什么。如果您尝试使用列表作为键,那么会出现什么问题,而哈希就是说它们的内存位置?

I had some vague idea that that the key has to be "hashable" but I'm just going to admit my own ignorance about the technical details; I don't know what's really going on here. What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

推荐答案

关于Python维基话题的好文章:为什么列表不能是字典键。如下所述:

There's a good article on the topic in the Python wiki: Why Lists Can't Be Dictionary Keys. As explained there:


如果您尝试使用列表作为键,哈希为例如内存位置会出错怎么办?

What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

可以在没有真正破坏任何要求的情况下完成,但会导致意外的行为。列表通常被视为它们的价值来源于其内容的值,例如在检查(in)相等时。许多人可以理解 - 希望您可以使用任何列表 [1,2] 获取相同的密钥,您必须保持完全相同的列表对象。但是,一旦用作关键字的列表被修改,就可以通过值中断进行查找,并且通过身份查询需要保持完全相同的列表 - 这对于任何其他通用列表操作是不需要的(至少我不能想到)

It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their content's values, for instance when checking (in-)equality. Many would - understandably - expect that you can use any list [1, 2] to get the same key, where you'd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list - which isn't requires for any other common list operation (at least none I can think of).

其他对象(如模块和对象)使它们的对象身份变得更大一点是最后一次你有两个不同的模块对象,称为 sys ?),并且被比较。因此,在用作dict键的情况下,在这种情况下也可以通过身份进行比较,这并不奇怪,甚至是预期的。

Other objects such as modules and object make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys?), and are compared by that anyway. Therefore, it's less surprising - or even expected - that they, when used as dict keys, compare by identity in that case as well.

这篇关于为什么我不能在python中使用列表作为dict键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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