Why no list as dict key?
Chris Angelico
rosuav at gmail.com
Wed Apr 20 15:49:33 EDT 2022
On Thu, 21 Apr 2022 at 05:30, Sam Ezeh <sam.z.ezeh at gmail.com> wrote:
>
> 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.
>
> ```
> >>> class HashableList(list):
> ... def __hash__(self):
> ... return functools.reduce(operator.xor, [key * value for
> key, value in enumerate(self)], 5)
Quickie: I'd be inclined to define hash on top of a tuple's hash,
rather than try to design my own and hope that it's suitable. "return
hash(tuple(self))" is a good demonstration of the parallel.
Otherwise, good demonstration of the problem.
ChrisA
More information about the Python-list
mailing list