Using dictionaries as switch statements in Python 2.7.3

I like to use dictionaries as a form of switchstatment, using booleans settings as keys. Example:

>>> def f(a):
...      return {True: -a, a==0: 0, a > 0: a}[True]
... 
>>> f(-3)
3
>>> f(3)
3
>>> f(0)
0

The key Trueworks as a case else/ defaultand is returned only if the other key is not evaluated in True. I guess this suggests some sort of evaluation order for iterating the dictionary.

Now check out the following snippet from the latest release from the Python team for the latest versions of branches 2.6, 2.7, 3.1, and 3.2

Hash randomization means that the iterations of dicts and set are unpredictable and different in all Python scripts. Python is never a guaranteed key iteration order in dict or set, and it is recommended that applications never rely on it. Historically, the dict iteration order has not changed very often across releases and always remained consistent between consecutive Python executions. Thus, some existing applications may rely on dict or set ordering.

Does this mean that using dicts as switch calls is no longer possible? Or maybe I should use any other class (e.g., OrderedDictor something else)? Or maybe I'm completely off, and this should not affect it at all?

+3
source
8

, .

: True False. True , .

.

+6

. , .

, , if..elif, ( ).

+5

, , . , , /. , - Python.

+3

, , , , . , , , , .

, , . , (, , - , ) , , (.. ). :

return ( a if a > 0  else
         0 if a == 0 else
        -a)
+2

-, , :

def f(a):
    d = {}
    d[True] = -a
    d[a==0] = 0
    d[a>0] = a
    return d[True]

.

? :

def f(a):
    return a if a > 0 else 0 if a == 0 else -a

, , , , , , - .

+2

, ( Python 3 ), . (: ) .

switch

, :

 {value1: one_func, value2: another_func, value3: third_func}

True/False, :

return one_func() if check else another_func()

if... return:

if check:
    return one_func()

return another_func() if another_check else third_func()

.

+1

, .

, boolean, .

:

switch = {
   choice1: func1
   choice1: func2
   ...
}

switch[variable]()
0

, , :

 mydict.values()[0]

, . , .

, , . :

if a == 0:
     return 0
elif a > 0:
     return a
else:
     return -a

Or, more briefly (but perhaps less readable) return 0 if a == 0 else a if a > 0 else -a, and a is 0, then it is a > 0never evaluated (and still will not even be if you are not returnabove it). Your dictionary should evaluate each key that you give it as a condition every time. The only reason to try using a dispatch dictionary instead of a chain ifis efficiency, but in the case when the keys are not constant and the whole dict is predefined, you can lose badly.

0
source

All Articles