Use a dict of functions

suggest change

Another straightforward way to go is to create a dictionary of functions:

switch = {
    1: lambda: 'one',
    2: lambda: 'two',
    42: lambda: 'the answer of life the universe and everything',
}

then you add a default function:

def default_case():
    raise Exception('No case found!')

and you use the dictionary’s get method to get the function given the value to check and run it. If value does not exists in dictionary, then default_case is run.

>>> switch.get(1, default_case)()
one
>>> switch.get(2, default_case)()
two
>>> switch.get(3, default_case)()
Exception: No case found!
>>> switch.get(42, default_case)()
the answer of life the universe and everything

you can also make some syntactic sugar so the switch looks nicer:

def run_switch(value):
    return switch.get(value, default_case)()

>>> run_switch(1)
one

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Alternatives to switch statement from other languages:
* Use a dict of functions

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
115 Alternatives to switch statement from other languages
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve