Python:为什么list不能作为字典(dict)的key

版权声明:如需转载或引用,请注明出处。 https://blog.csdn.net/weixin_39278265/article/details/84956053

参考文献

[1] https://wiki.python.org/moin/DictionaryKeys
这里是最权威的官方解释。
大概就是:设计就是这样的,python中list的性质决定了不能用hash函数来操作。
所以list是没有__hash__方法的(为None),故而不能做字典的key。
但是tuple有__hash__方法,所以可以做字典的key。

感觉这个网站非常好:https://wiki.python.org
各种python知识。

[2] 什么样的类型可以作为python字典的key https://blog.csdn.net/eshaoliu/article/details/51852504

[3] Why can’t I use a list as a dict key in python? https://stackoverflow.com/questions/7257588/why-cant-i-use-a-list-as-a-dict-key-in-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?
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).


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.

[4] Python 为什么list不能作为字典的key? https://blog.csdn.net/sinat_32547403/article/details/73613222
这个是从[1]翻译过来的。

[5] python中list/tuple/dict/set的区别 https://www.cnblogs.com/shengulong/p/7149832.html
科普文,介绍了一下set。

猜你喜欢

转载自blog.csdn.net/weixin_39278265/article/details/84956053