Generic dictionary

Thorsten Kampe thorsten at thorstenkampe.de
Sun Nov 20 08:12:02 EST 2016


* Chris Angelico (Sun, 20 Nov 2016 23:35:52 +1100)
> I see. So you want to be able to have something that looks and 
> feels
> like a dictionary, but uses a different way of looking things up.
> Makes reasonable sense, on the surface.
> 
> Before you go down that route, I strongly recommend reading up on
> exactly *why* a dictionary has the requirement of hashability, and
> what the consequences are of trying to look things up using lists as
> keys. You can easily experiment with it like this:
> 
> class HashableList(list):
>     def __hash__(self):
>         return hash(tuple(self))
> 
> Use those in your dict, rather than vanilla lists. Then you can mess
> around with the consequences of mutable dict keys.
> 
> Alternatively, switch from using lists to using tuples. They're
> hashable and immutable, thus avoiding the problems. If what you're
> trying to do is use multi-part dict keys, a tuple is far and away the
> best solution.

Chris, it's up to the consumer to decide which key/keyfunc to use. 
The lists as keys (that is first element in an tuple) are created on 
the fly and not used for anything. They are mutable but not mutated.

Mutating the list would be like mutating a list you're iterating 
through: just don't do it.

Thorsten




More information about the Python-list mailing list