Best way to hash a dictionary

Mike Meyer mwm at mired.org
Mon Mar 3 12:14:40 EST 2003


Alex Martelli <aleax at aleax.it> writes:
> The obvious idea would be something like:
> 
> class HashableDict(dict):
>     def __init__(self, *args, **kwds):
>         dict.__init__(self, *args, **kwds)
>         my_hash = 0
>         for key in self: my_hash ^= hash(key)
>         self.my_hash = my_hash
>     def __hash__(self):
>         return self.my_hash

The idea that struc me as obvious - and survives in the face of
mutating the dictionary after creating it - was:

class HashableDict(dict):
    def __hash__(self): return id(self)

Which guarantees unique hash keys. The downside is that two identical
dictionaries won't have the same value.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list