[portland] Dictionary To Switch Contexts

Michael Richardson richardson.michael.t at gmail.com
Mon Mar 17 23:55:20 CET 2008


>    I miss seeing how I can create a function to provide the value when given
> the key. My code uses the item within the tuple (compList[0][4]) as the
> dictionary's key, and I want to call the function whose name is the value of
> that key.

Python returns the actual function when you get it via the dict - so you 
can just call it directly.  For example:

 >>> def times_two(value):
...   return value*2
...
 >>> def times_one(value):
...   return value
...
 >>> func_dict = {'bytwo': times_two, 'byone': times_one}
 >>> func_dict['bytwo'](4)
8
 >>> func_dict['byone'](4)
4
 >>>





More information about the Portland mailing list