[Tutor] Using dictionaries to call functione

alan.gauld@bt.com alan.gauld@bt.com
Sat, 18 Aug 2001 22:07:19 +0100


> For example, I would like to pass a list of words and parameters to a
> function, and for each word in the list, call word(parameter1,
> parameter2, ...) referenced in a dictionary which somehow calls the
> associated function (called a "dispatch table", I think).  

You mean something like this:

val = (word, p1,p2,p3) # the data
dict[word](p1,p2,p3)   # the call via a dict?

If so you set up the dict with the key being a string equal to 
the functions name and the va;lue being a reference to the 
function object

Something like:

# define 3 functions
def foo(a): return a
def bar(a,b): return a+b
def baz(c): return `c`

# create dictionary keyed by function name
dict = {'foo':foo, 'bar':bar, 'baz':baz}

Now you have to know what params are needed for each function.
Things like apply and **args etc might alleviate that pain.

Does that help?

Alan g