Generic dictionary

Chris Angelico rosuav at gmail.com
Sun Nov 20 07:35:52 EST 2016


On Sun, Nov 20, 2016 at 11:19 PM, Thorsten Kampe
<thorsten at thorstenkampe.de> wrote:
> The whole point of my posting was non hashable keys (like lists):
>
> ```
>>>> dictitem
> [([1], '11'), ([2], '22'), ([4], '33'), ([3], '44')]
>>>> dict(dictitem)
> ---------------------------------------------------------------------
> TypeError                           Traceback (most recent call last)
> <ipython-input-12-0f2b626ac851> in <module>()
> ----> 1 dict(dictitem)
>
> TypeError: unhashable type: 'list'
> ```

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.

ChrisA



More information about the Python-list mailing list