Possibly dumb question about dicts and __hash__()
Peter Otten
__peter__ at web.de
Thu May 4 02:48:01 EDT 2006
Joel Hedlund wrote:
> There's one thing about dictionaries and __hash__() methods that puzzle
> me. I have a class with several data members, one of which is 'name' (a
> str). I would like to store several of these objects in a dict for quick
> access ({name:object} style). Now, I was thinking that given a list of
> objects I might do something like
>
> d = {}
> for o in objects:
> d[o] = o
>
> and still be able to retrieve the data like so:
>
> d[name]
>
> if I just defined a __hash__ method like so:
>
> def __hash__(self):
> return self.name.__hash__()
Just the hash is not enough. You need to define equality, too:
>>> class Named(object):
... def __init__(self, name):
... self.name = name
... def __hash__(self):
... return hash(self.name)
... def __eq__(self, other):
... try:
... other_name = other.name
... except AttributeError:
... return self.name == other
... return self.name == other_name
... def __repr__(self):
... return "Named(name=%r)" % self.name
...
>>> items = [Named(n) for n in "alpha beta gamma".split()]
>>> d = dict(zip(items, items))
>>> d["alpha"]
Named(name='alpha')
Peter
More information about the Python-list
mailing list