Retrieve an item from a dictionary using an arbitrary object as the key

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Apr 3 21:35:25 CEST 2007


abcd a écrit :
>>You'll need __eq__ for testing if two objects are equivalent, and
>>__hash__ for calculating object's hash value.
>>
>>class Type:

While we're at it, and unless you're stuck with an aging Python version, 
make Type and Person new-style classes:

class Type(object):

>>    def __init__(self, val):
>>        self.val = val
>>
>>    def __eq__(self, other):
>>        return self.val == other.val
>>
>>    def __hash__(self):
>>        return hash(self.val)
> 
> 
> that's exactly what I needed, thanks.
> 

And to answer your original question, ie "I am thinking there is some 
method that is used by the dictionary to know if the key exists, just 
not sure which.", you can:

- test if a dict as a given key:

d = {"a" : 42, "b" : "foo"}
"a" in d
=> True
"x" in d:
=> False

- and/or use dict.get(key, default=None):

d.get("a")
=> 42
d.get("x")
=> None
d.get("x", "woops")
=> "woops"

HTH






More information about the Python-list mailing list