Python Switch Case Statements

by James Johnson

Unlike most programming languages, Python does not contain a switch statement. However, similar and potentially more advantageous functionality can be implemented in Python using dictionary mappings.

Python Switch/Case via Dictionary Mapping

In places in my code where I may have normally used switch and/or case statements, I have developed the habit of using dictionary mappings to quickly lookup handlers for specific values:

def web_view(request, category):
    mapping = {
        "fun": _handle_fun_request,
        "boring": _handle_boring_request,
    }

    if category.lower() not in mapping:
        return HttpResponse("", status=404)

    return mapping[category.lower()](request)

def _handle_fun_request(request):
    # ... do something fun

def _handle_boring_request(request):
    # ... do something boring

One of the benefits of using a dictionary-based mapping is that it can be dynamically created or updated.

Thoughts

Although slightly annoying, not having built-in switch/case statements was no longer a hindrance once I found a way to implement similar functionality using dictionaries.