Hashtable as Switch Statement
When you see a dictionary data structure, do you think “Ah, it's a flow control”?
in programing, we often do coolness.
Python doesn't have {switch, case, cond} constructs. Someone asked about it on stackoverflow [http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python]
, and this is the most up-voted answer:
# python 3 # emulating “switch” statement by dictionary # works in both python 2 and 3 def f(x): return { "a": 1, "b": 2, }.get(x, 9) # 9 is default if x not found # test y = "d" print(f(y)) # 9
you use a dictionary to emulate switch statement.
It is cool, but there is serious problems:
- it is extremely inefficient.
- the intention of the programer isn't explicit.
here's a simpler, more verbose, version, but the programer intention is clear, and much easier to understand.
# python 3 # multiple if statement, similar to “switch” conditional def f(x): if x == "a": return 1 if x == "b": return 2 return 9 y = 2 print(f(y))