Dispatching functions from a dictionary

Paul Rubin http
Sun Mar 30 17:06:18 EDT 2008


tkpmep at gmail.com writes:
> RVDict= {'1': random.betavariate(1,1),     '2': random.expovariate(1), ...}

This actually calls the functions random.betavariate, etc.  when
initializing RVDict.  If you print out the contents of RVDict you'll see
that each value in it is just a floating point number, not a callable.

You want something like:

  RVDict = {'1': lambda: random.betavariate(1,1),
            '2': lambda: random.expovariate(1),     etc.

The "lambda" keyword creates a function that when called evaluates the
expression that you gave it.  For example, lambda x: x*x   is a function
that squares its argument, so saying
     
    y = (lambda x: x*x) (3)

is similar to saying:

    def square(x): return x*x
    y = square(3)

Both of them set y to 9.  In the case of lambda: random.expovariate(1)
you have made a function with no args, so you'd call it like this:

> rvfunc = RVDict[str(RVType)]
> for i in range(N):
>     x.append(rvfunc())
>     y.append(rvfunc())

rvfunc (the retrieved dictionary item) is now a callable function
instead of just a number.  It takes no args, so you call it by saying
rvfunc().



More information about the Python-list mailing list