Python Tutorial Python Advanced Python References Python Libraries

Python - Switch Case Implementation



Unlike C++/Java, Python does not have a built-in switch case statement. Due to this, it is quite common to think of using if-elif-else control statement for each switch cases. But there is a other way around to implement switch statement in Python. The powerful dictionary mapping which provides unique key-value mapping can be efficiently used to create such implementation.

Example:

The example below illustrates how to implement switch case in Python. Inside the function called MySwitchCases, the dictionary called MyDict is created with key-value pairs representing respective switch-case scenarios. When the function MySwitchCases is called, it uses dictionary get() method to find the value of the specified key. If the key is not present in the dictionary, it returns default value which is "Not Found" in this particular example.

def MySwitchCases(case):
  MyDict = {
    1: 'MON',
    2: 'TUE',
    3: 'WED',
    4: 'THU',
    5: 'FRI',
    6: 'SAT',
    7: 'SUN'
  }
  
  return MyDict.get(case, 'Mapping not found')

print("3 is Mapped to:", MySwitchCases(3))
print("9 is Mapped to:", MySwitchCases(9))

The output of the above code will be:

3 is Mapped to: WED
9 is Mapped to: Mapping not found

❮ Python - Dictionary