A switch statement for Python
Many languages support a control structure called the switch statement that is an alternative for if/else-if. Python, however, has no switch statement. Does that mean we must always resort to using a sequence of if/elif? Not necessarily!
Python uses one of the most efficient hashing algorithms for it’s dictionary type. We can use a dictionary to create a type of switch statement that is both efficient and very elegant. Consider the following sequence of if/elif to find a holiday for a given month.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
month = 'March'
if month.lower() == "january":
holiday = "New Year"
if month.lower() == "february":
holiday = "Valentine's Day"
elif month.lower() == "march":
holiday = "St. Patrick's Day"
elif month.lower() == "april":
holiday = "Easter"
elif month.lower() == "may":
holiday = "Mother's Day"
elif month.lower() == "june":
holiday = "Father's Day"
elif month.lower() == "july":
holiday = "Independence Day"
elif month.lower() == "august":
holiday = "Lemonade Stand Day"
elif month.lower() == "september":
holiday = "Labor Day"
elif month.lower() == "october":
holiday = "Holloween"
elif month.lower() == "november":
holiday = "Thanksgiving"
elif month.lower() == "december":
holiday = "Christmas"
else:
holiday = "Error: Invalid month!"
print holiday
This can be made much more readable and pythonic by using a dictionary.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
month = 'March'
holiday = {"january":"New Year",
"february":"Valentine's Day"
"march":"St. Patrick's Day"
"april":"Easter"
"may":"Mother's Day"
"june":"Father's Day"
"july":"Independence Day"
"august":"Lemonade Stand Day"
"september":"Labor Day"
"october":"Holloween"
"november":"Thanksgiving"
"december":"Christmas"}.get(month.lower(), "Error: Invalid month!")
print holiday
You can read more about python dictionaries at http://docs.python.org/tutorial/datastructures.html#dictionaries
Comments: