Python Dictionary as Switch Statement

By Xah Lee. Date: . Last updated: .

Some people are using dictionary as a switch statement. How idiotic.

this is a situation where syntactic simplicity leads to inefficiency.

When you see a dictionary, do you think flow control?

# 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

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.

you use a dictionary to emulate switch statement.

It is cool, but there are problems:

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