dict's as dict's key.

Peter Otten __peter__ at web.de
Wed Jan 13 20:28:14 CET 2010


Albert van der Horst wrote:

> I have a type of objects that have complicated enough properties
> to warrant a special class for its type.
> The class has built in dictionary for all the properties.
> 
> Something along the line of
> a = ctype({"poker":True})
> b = ctype({"footbal":True, "gender":"m"})
> c = ctype({"chess":True, "residence":"Amsterdam"})
> I can count each type, again using a dictionary:
> db = {}
> db[a]=171
> db[b]=208
> 
> But now I am at a loss as how to look up a ctype z in this db
> dictionary efficiently, because all those objects are different
> from z.
> 
> Is there a way to turn those ctype things into a hashable type?
> (I would then convert z in the same way.)
> Once a ctype is invented it never changes.
> The only data pertinent to a ctype is its property dictionary.

>>> class CType:
...     def __init__(self, data):
...             self.data = data
...             self._hash = hash(tuple(sorted(data.iteritems())))
...     def __hash__(self):
...             return self._hash
...     def __eq__(self, other):
...             return self._hash == other._hash and self.data == other.data
...
>>> a = CType({"poker":True})
>>> b = CType({"footbal":True, "gender":"m"})
>>> c = CType({"chess":True, "residence":"Amsterdam"})
>>> db = {}
>>> db[a]=171
>>> db[b]=208
>>> db[CType(dict(poker=True))]
171
>>> CType(dict(poker=False)) in db
False

Be very careful not to change the dictionary in the data attribute. 
Otherwise you'll break your application.

Peter



More information about the Python-list mailing list