Why no list as dict key?

Sam Ezeh sam.z.ezeh at gmail.com
Wed Apr 20 15:28:41 EDT 2022


Repeating the above points, here is an example of what would happen if
you tried. Dictionaries require their keys to be immutable as
under-the-hood they use hash tables and they'd fail when the
underlying values are allowed to change.

```
[sam at samtop]: ~>$ python
Python 3.10.2 (main, Jan 15 2022, 19:56:27) [GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import functools
>>> import operator
>>> class HashableList(list):
...     def __hash__(self):
...             return functools.reduce(operator.xor, [key * value for
key, value in enumerate(self)], 5)
...
>>> x = HashableList([1,2,3])
>>> y = HashableList([1,2,3])
>>> dictionary = {x: 5}
>>> dictionary
{[1, 2, 3]: 5}
>>> dictionary[x]
5
>>> dictionary[y]
5
>>> x.append(4)
>>> dictionary
{[1, 2, 3, 4]: 5}
>>> dictionary[x]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: [1, 2, 3, 4]
>>> dictionary[y]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: [1, 2, 3]
>>>
```

On Wed, 20 Apr 2022 at 19:23, Abdur-Rahmaan Janhangeer
<arj.python at gmail.com> wrote:
>
> Greetings list,
>
> Using Python3.9, i cannot assign a list [1, 2] as key
> to a dictionary. Why is that so? Thanks in advanced!
>
> Kind Regards,
>
> Abdur-Rahmaan Janhangeer
> about <https://compileralchemy.github.io/> | blog
> <https://www.pythonkitchen.com>
> github <https://github.com/Abdur-RahmaanJ>
> Mauritius
> --
> https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list