This does raise an issue, Chris, if you use the method of making a tuple 
companion for a list at a specific time just for use as a dictionary key, then 
later change the list, you can end up with various situations.
Obviously the changed list can not only not access the stored item, but if 
converted again to a tuple, may address a different item. I can see many 
scenarios with abandoned dictionary items that are never deleted and can only 
be reached by examining all items in the dictionary.
So mutability is only one concern. If you actually mutate your data, ...
I am thinking as an example about a program I wrote ages ago that deals with 
equations in symbolic form and maintains a collection of forms of the equation 
it is trying to take a derivative or integral of by applying an assortment of 
typographic rules. I mean commutative lawand others. You do not want to  keep 
adding the same item into the data structure (such as a queue) repeatedly. So 
something like a dictionary (or set) can be a good way to store unique items. 
But the items are some complex lists so the above discussion qualifies. Of 
course the tuple conversion for a nested structure would need to have made a 
deep copy. 
The question in the above is how to make sure that taking a next attempt off 
the queue deals with the dictionary of tried items. In this case, unless you 
use it to find a solution, keeping it in the dictionary to avoid repeating, 
makes sense. 
And another thought is that mapping a list to a tuple has another possible 
drawback.
What if I have both a list and tuple with the same structure which I want as 
keys?
I can imagine then converting the list in some imaginative ways. For example, 
embed the list in another list whose first item is "from-tuple" or something. 
Life is complicated. Then you die.


-----Original Message-----
From: Chris Angelico <ros...@gmail.com>
To: python-list@python.org
Sent: Wed, Apr 20, 2022 3:49 pm
Subject: Re: Why no list as dict key?

On Thu, 21 Apr 2022 at 05:30, Sam Ezeh <sam.z.e...@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
-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to