Emulating switch/case Statements in Python

Python doesn’t have switch/case statements so it’s often necessary to write long if/elif/else chains as a workaround. Here’s a little trick you can use to emulate switch/case statements in Python using dictionaries and first-class functions.

Basically we’re using Python dictionaries as a lookup table to replace a nested “if elif else” statement with a cleaner and more maintainable implementation.

In some cases this can be faster than if-then-else chains and easier to maintain, too. To see if this method is right for you watch the video tutorial and learn how to apply this technique to write nice and clean Python.

What’s Included:

About Dan Bader

Dan Bader is the owner and editor in chief of Real Python and the main developer of the realpython.com learning platform. Dan has been writing code for more than 20 years and holds a master's degree in computer science.

» More about Dan

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

« Browse All Courses