Dictionaries with variable default.

Cousin Stanley cousinstanley at gmail.com
Tue Nov 4 09:13:54 EST 2014


> So How should I call this:
> 
> class ...dict(dict):
>     def __init__(self, fun):
>         self.fun = fun
> 
> def __missing__(self, key):
>     return self.fun(key)

  I don't know how you should,
  but I tried the following 
  which seems to work .... 

class KeyPlusOne( dict ) :
    def __missing__( self , key ) : 
        return ( 2 * key ) + 1 

kp1 = KeyPlusOne()

d   = { }

for n in range( 11 ) :  
    d[ n ] = kp1[ n ]

print '\n   key :  value \n'

for key , value in d.iteritems() : 
    print '    %2d :  %2d' % ( key , value )


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona



More information about the Python-list mailing list