Hashtable as Switch Statement

By Xah Lee. Date: . Last updated: .

When you see a hash table, 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 hash table (aka dictionary) to emulate switch statement.

It is cool, but there is a problem: the intention of the programer isn't explicit. Instead, you have to engage your brain to figure out what it's supposed to do.

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))

Programing Idioms and Style

  1. Programing Elegance vs Simplicity
  2. Why Idioms Are Bad
  3. The Nature of Idioms in Programing Languages
  4. Hashtable as Switch Statement
  5. Logic Operator as Control Flow

If you have a question, put $5 at patreon and message me.