[portland] Fwd: Dictionary As Switch Statement

Kirk McDonald kirklin.mcdonald at gmail.com
Fri Jan 18 22:23:00 CET 2008


Okay, here's that message again.

---------- Forwarded message ----------
From: Kirk McDonald <kirklin.mcdonald at gmail.com>
Date: Jan 17, 2008 4:47 PM
Subject: Re: [portland] Dictionary As Switch Statement
To: Rich Shepard <rshepard at appl-ecosys.com>



On Jan 17, 2008 4:16 PM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
>    I want to use a dictionary to select the appropriate function to call
> based on the key value. However, I'm missing something simple here as I try
> to implement it.
>
>    The dictionary:
>
>      curvePlot = {
>        'Decay S-Curve'     : zCurve(self),
>        'Bell Curve'        : bellCurve(self),
>        'Growth S-Curve'    : sCurve(self),
>        'Beta'              : betaCurve(self),
>        'Data'              : dataCurve(self),
>        'Linear Increasing' : linIncrCurve(self),
>        'Linear Decreasing' : linDecrCurve(self),
>        'Left Shoulder'     : leftShouldCurve(self),
>        'Trapezoid'         : trapCurve(self),
>        'Right Shoulder'    : rightShouldCurve(self),
>        'Triangle'          : triangCurve(self),
>        'Singleton'         : singleCurve(self),
>        'Rectangle'         : rectCurve(self),
>        'Outcome'           : resultsCurve(self)
>        }
>
>    I can print out the keys, in a different order; 'print curvePlot.keys()'
> yields:
>
> ['Left Shoulder', 'Singleton', 'Outcome', 'Bell Curve', 'Right
> Shoulder', 'Growth S-Curve', 'Beta', 'Linear Increasing', 'Decay S-Curve',
> 'Linear Decreasing', 'Trapezoid', 'Triangle', 'Data', 'Rectangle']
>
>    But, when I try to print the entire dictionary, the values are not shown;
> 'print curvePlot' produces:
>
> {'Left Shoulder': None, 'Singleton': None, 'Outcome': None, 'Bell Curve':
> None, 'Right Shoulder': None, 'Growth S-Curve': None, 'Beta': None, 'Linear
> Increasing': None, 'Decay S-Curve': None, 'Linear Decreasing': None,
> 'Trapezoid': None, 'Triangle': None, 'Data': None, 'Rectangle': None}
>
>    What have I done incorrectly that I cannot produce the value for a given
> key? When I pass the value of the key (it's the fifth item in a tuple so
> it's addressed as 'row[4]') all I get is 'None.'
>
> Rich
>

The values in the dictionary should be the function objects
themselves. For example:

def f(x):
    print x*2

def g(x):
    print x*10

switch = {
    'f': f,
    'g': g,
}

You should only call the function after you index the dictionary:

switch['f'](10) # prints 20

This implies that all of the callables in the dictionary must have
compatible parameters.


More information about the Portland mailing list