[portland] Dictionary To Switch Contexts

Dylan Reinhardt python at dylanreinhardt.com
Mon Mar 17 21:53:20 CET 2008


Here's a simplified example of how that might work... hope this helps:

----
def doA():
    pass

def doB():
    pass

switcher = {
    'a': doA,
    'b': doB
    }

x = someFunction()  # returns 'a' or 'b'

switcher[x]()
----

With obvious changes if you want to pass arguments, check switcher with
.get(), etc.

Dylan




On 3/17/08, Rich Shepard <rshepard at appl-ecosys.com> wrote:
>
>    Rather than using multiple if ... elif ... statements, I'm trying to
> implement a dictionary to call the proper function based on the value
> passed
> to it. I don't know how to express the value when a key is selected.
>
>    Here's the dictionary:
>
> curvePlot = {
>        'Decay S-Curve'     : zCurve,
>        'Bell Curve'        : bellCurve,
>        'Growth S-Curve'    : sCurve,
>        'Beta'              : betaCurve,
>        'Data'              : dataCurve,
>        'Linear Increasing' : linIncrCurve,
>        'Linear Decreasing' : linDecrCurve,
>        'Left Shoulder'     : leftShouldCurve,
>        'Trapezoid'         : trapCurve,
>        'Right Shoulder'    : rightShouldCurve,
>        'Triangle'          : triangCurve,
>        'Singleton'         : singleCurve,
>        'Rectangle'         : rectCurve,
>        'Outcome'           : resultsCurve
>        }
>
>   These curve are actually in a separate module, 'functions,' but python
> doesn't like me to put the function name in the dictionary, so I have
> helper
> functions in the dictionary's module.
>
>    Here's how I'm trying to use the dictionary:
>
> if compList[0][1] == curVar:
>              # call plotting function
>              pylab.hold(True)
>              curvePlot.get(compList[0][4], ???)
>
>    I don't know what to write where the question marks are. The item at
> compList[0][4] is a string that matches one of the dictionary keys.
>
> Rich
>
>
> --
> Richard B. Shepard, Ph.D.
> |  Integrity            Credibility
> Applied Ecosystem Services, Inc.        |            Innovation
> <http://www.appl-ecosys.com>     Voice: 503-667-4517      Fax:
> 503-667-8863
> _______________________________________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/mailman/listinfo/portland
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/portland/attachments/20080317/884c4657/attachment.htm 


More information about the Portland mailing list