No switch-case in python ?

I guess everyone starting out developing in python eventually runs into a situation where a good old switch-case would be necessary, turns out there’s no such thing in python, but there is a pretty handy alternative, so here is what i found out.

Python dictionarys are great, you can simply define any kind of mapping such as the following: 

DICT = {
“home”: “/Users/me/home”,
“share”: “/Users/share”,
“dl”: “/Volumes/dl”,
“backup”:”/Volumes/backup”,
 }

and access an element by it’s key like this:

path = DICT.get(“home”)

now assume you have a variable <userInput> that you usually would run through a switch-case in order to evaluate.
By defining a dictionary like the one above, you can do it in just one simple line:

path = DICT.get(userInput)

I really like this, because it makes code more reusable, you could even define a dictionary of methods and “virtually” switch-case through them.

happy coding

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: