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

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

问题描述

我对什么可以/不能用作 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 wiki 中有一篇关于该主题的好文章:为什么列表不能是字典键.正如那里所解释的:

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?

它可以在不违反任何要求的情况下完成,但会导致意外行为.列表通常被视为它们的值来自其内容的值,例如在检查(不)相等性时.许多人 - 可以理解 - 期望您可以使用任何列表 [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).

其他对象,例如模块和 object 无论如何都要利用它们的对象标识做更多的事情(你上一次拥有两个不同的模块对象,称为 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 中使用列表作为字典键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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