Using Dictionaries in Sets - dict objects are unhashable?

Jonathan Gardner jgardner at jonathangardner.net
Tue Mar 21 19:43:41 EST 2006


Welcome to Python, where all types are either static (and thus
hashable) or volatile (and thus not hashable.)

The way hash tables work (which is what powers the set and dict types),
you have to be able to get a number from an instance of the type, with
the following conditions true:

(1) Every equivalent instance (whatever that means to you) will give
you the same number for the type.

(2) You always get the same number for the instance of the type.
(Because things should be equal to themselves.)


If these two things don't hold true, then the hash tables won't work
like you would expect them to. (Imagine punching in the same dict that
has been modified slightly as the key. What do you expect to get back?)

You *could* create a dict that hashes off of its unique id. But the id
isn't really unique because old ids get recycled.

You *could* convert the dict to a tuple of key-value pairs, and then
hash that, but every value in that tuple would have to be hashable.

Instead of storing the dicts in the set, trying storing something else
that is hashable, and invent some way of "remembering" which thing
refers to which dict.




More information about the Python-list mailing list