0
0
PythonHow-ToBeginner · 3 min read

Python Switch Case Equivalent: How to Use match-case and Dict Mapping

Python does not have a traditional switch statement, but you can use the match-case statement introduced in Python 3.10 or dictionary mapping to achieve similar behavior. The match-case syntax is the closest equivalent and allows clear, readable branching based on values.
📐

Syntax

The match-case statement in Python works like a switch case. You write match followed by a variable, then use case blocks for each value to check. A case _ acts like a default case.

  • match variable: Start the pattern matching on the variable.
  • case value: Check if variable equals this value.
  • case _: Catch-all if no other case matches.
python
def switch_example(value):
    match value:
        case 1:
            return "One"
        case 2:
            return "Two"
        case _:
            return "Other"
💻

Example

This example shows how to use match-case to print a message based on a number. It demonstrates matching specific cases and a default case.

python
def describe_number(num):
    match num:
        case 0:
            return "Zero"
        case 1:
            return "One"
        case 2:
            return "Two"
        case _:
            return "Something else"

for i in range(4):
    print(f"Input: {i} -> Output: {describe_number(i)}")
Output
Input: 0 -> Output: Zero Input: 1 -> Output: One Input: 2 -> Output: Two Input: 3 -> Output: Something else
⚠️

Common Pitfalls

One common mistake is trying to use match-case in Python versions before 3.10, which will cause a syntax error. Another is forgetting the case _ default case, which can lead to no match found. Also, dictionary mapping is often used as a switch case alternative but beware of calling functions immediately instead of passing them.

python
def wrong_dict_switch(value):
    switch = {
        1: print("One"),  # This calls print immediately, not when key matches
        2: print("Two")
    }
    return switch.get(value, lambda: print("Other"))

# Correct way:

def correct_dict_switch(value):
    switch = {
        1: lambda: print("One"),
        2: lambda: print("Two")
    }
    func = switch.get(value, lambda: print("Other"))
    func()
📊

Quick Reference

ConceptPython EquivalentNotes
switch statementmatch-case (Python 3.10+)Use for clear multi-case branching
case/defaultcase value / case _Underscore is default case
switch with functionsDictionary mapping with lambdasPass functions, don't call immediately
Older Python versionsDictionary mappingNo match-case support before 3.10

Key Takeaways

Use Python 3.10+ match-case for the clearest switch case equivalent.
Always include a default case with case _ to handle unmatched values.
Dictionary mapping with lambdas is a good alternative for function calls.
Avoid calling functions immediately in dictionary switch alternatives.
match-case is not available before Python 3.10 and will cause errors.