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

irstas at gmail.com irstas at gmail.com
Tue Apr 3 12:30:55 EDT 2007


On Apr 3, 7:26 pm, "abcd" <codecr... at gmail.com> wrote:
> Hi,
>     I have a class such as,
>
> class Type:
>     def __init__(self, val):
>         self.val = val
>
> class Person:
>     def __init__(self, name, age):
>         self.name = name
>         self.age = age
>
> So I have a dictionary which maps an instance of Type to an instance
> of Person.  Now I need to retrieve a particular Person given a Type
> object.  What method in Type do I need to implement to allow it to be
> retrieved?
>
> For example (this is just an example):
>
> t = Type(19)
> p = Person("bob", 99)
>
> x = {t : p}
>
> ....<later on in the code somewhere>....
>
> def getPerson(val):
>     return x[Type(val)]
>
> getPerson(19)  ....should return me the Person with name "bob" and age
> 99.  I am thinking there is some method that is used by the dictionary
> to know if the key exists, just not sure which.
>
> thanks

You'll need __eq__ for testing if two objects are equivalent, and
__hash__ for calculating object's hash value.

class Type:
    def __init__(self, val):
        self.val = val

    def __eq__(self, other):
        return self.val == other.val

    def __hash__(self):
        return hash(self.val)





More information about the Python-list mailing list