Wednesday, May 20, 2015

How to use custom type as dictionary key in Python

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Steps :
Implement a custom key class  and override hash and equality function.

e.g.

class CustomDictKey(object):

    def __init__(self, 
                 param1,
                 param2):
    
                self._param1 = param1
                self._param2 = param2
              
    def __hash__(self):
        return hash((self._param1,
                 self._param2))

    def __eq__(self, other):
        return ( ( self._param1,
                 self._param2 ) == ( other._param1,
                 other._param2) )
                
    def __str__(self):
        return "param 1: {0} param 2: {1}  ".format(self._param1, self._param2)

if __name__ == '__main__':

    # create custom key
    k1  = CustomDictKey(10,5)
    
    k2  = CustomDictKey (2, 4)
    
    dictionary = {}
    
    #insert elements in dictionary with custom key
    dictionary[k1] = 10
    dictionary[k2] = 20
    
    # access dictionary values with custom keys and print values
    print "key: ", k1, "val :", dictionary[k1]
    print "key: ", k2, "val :", dictionary[k2]

               

No comments:

Post a Comment