Two Replacements for Switch Statements in Python

Two Replacements for Switch Statements in Python
Two Replacements for Switch Statements in Python.This method takes advantage of Python’s dictionary data type to achieve similar results: matching a case (key) and allowing a default value using `.get()`

Other programming languages such as JavaScript employ switch statements, which is a code block where a value is matched against a set of cases. When a case is matched, the code within that block (and everything thereafter) is executed. Optionally, a default case may be used as a catch-all when no cases are matched.

Switch statements are not present in Python; however, there are ways of emulating their behavior. Here are two methods for doing so.

Using a Dictionary Function with .get()

This method takes advantage of Python’s dictionary data type to achieve similar results: matching a case (key) and allowing a default value using .get()

def switch_dict(x):
   case_dict = {
      "a": 1,
      "b": 2,
      "c": 3
   }
   default_value = -1
   return case_dict.get(x, default_value)

To optimize our code and condense it further, we can write it as follows:

def switch_dict(x):
   return {
      "a": 1,
      "b": 2,
      "c": 3
   }.get(x, -1)

Notice the dictionary is within the function, which could be more efficient, but it’s easier to read and maintain this way.

Reconstructing With if/elif/else Statements

There’s always the oldie but goodie of using a sequence of if, elif, and else statements to recreate the switch statement.

def switch_dict(x):
   if x == "a":
      return 1
   elif x == "b":
      return 2
   elif x == "c":
      return 3
   else:
      return -1

This may seem more laborious than the simple dict; however, it does have advantages. If you need to perform multiple actions within each case, then using if statements will be easier to manage. Moreover, if statements will be beneficial for allowing more complex match conditions.

Suggest:

Python Tutorials for Beginners - Learn Python Online

Learn Python in 12 Hours | Python Tutorial For Beginners

Complete Python Tutorial for Beginners (2019)

Python Tutorial for Beginners [Full Course] 2019

Python Programming Tutorial | Full Python Course for Beginners 2019

Introduction to Functional Programming in Python