This One Python Feature Can Replace Half Your Conditionals

It didn’t just simplify my logic. It made my code actually fun to read again.

This One Python Feature Can Replace Half Your Conditionals
Photo by Lucas Santos on Unsplash

I used to write long, repetitive conditionals — until one Python feature made most of them disappear.

This One Python Feature Can Replace Half Your Conditionals

“Simple is better than complex.” — The Zen of Python

Conditionals are everywhere in Python code.

We use them to check conditions, make decisions, and control the flow of our programs.

But what if I told you that one Python feature could replace half of the if-else statements in your code — and make it cleaner, faster, and more Pythonic?

Let me introduce you to the dictionary dispatch pattern — an elegant alternative to repetitive if-elif-else chains.


The Problem: Too Many Conditionals

If you’ve ever written code like this:

def handle_action(action): 
    if action == 'start': 
        start() 
    elif action == 'stop': 
        stop() 
    elif action == 'pause': 
        pause() 
    elif action == 'resume': 
        resume() 
    else: 
        raise ValueError("Unknown action")

You’re not alone. This pattern is common — but as the number of conditions grows, so does the mess.

It becomes:

  • Harder to read
  • Slower to execute
  • More error-prone to maintain

That’s where dictionary-based dispatching comes in.

The Better Way: Function Dispatch with Dictionaries

Here’s the same logic, rewritten using a dictionary:

def handle_action(action): 
    actions = { 
        'start': start, 
        'stop': stop, 
        'pause': pause, 
        'resume': resume 
    } 
 
    try: 
        actions[action]() 
    except KeyError: 
        raise ValueError("Unknown action")

Python functions are first-class objects — meaning they can be stored in variables, passed as arguments, and used like any other object.

In this case, the actions dictionary maps strings to functions.

When an action comes in, we look it up and call the corresponding function, just like that.

No conditionals. No elif ladders. Just clean, efficient dispatching.

Real-World Example: Calculator App

Let’s look at a slightly more practical example — a basic calculator:

Traditional Conditional Style

def calculate(a, b, operation): 
    if operation == 'add': 
        return a + b 
    elif operation == 'subtract': 
        return a - b 
    elif operation == 'multiply': 
        return a * b 
    elif operation == 'divide': 
        return a / b 
    else: 
        raise ValueError("Invalid operation")

Dictionary Dispatch Style

def calculate(a, b, operation): 
    operations = { 
        'add': lambda: a + b, 
        'subtract': lambda: a - b, 
        'multiply': lambda: a * b, 
        'divide': lambda: a / b 
    } 
 
    try: 
        return operations[operation]() 
    except KeyError: 
        raise ValueError("Invalid operation")

Cleaner. More readable. Easier to extend (just add a new key to the dictionary!).

Bonus: Default Behavior with dict.get

Want to avoid try-except? You can use dict.get() with a default fallback function:

def handle_action(action): 
    actions = { 
        'start': start, 
        'stop': stop, 
        'pause': pause, 
        'resume': resume 
    } 
 
    default = lambda: print("Unknown action") 
    actions.get(action, default)()

Simple and effective.

When Not to Use It

This pattern isn’t a silver bullet. Avoid using it if:

  • The logic inside each condition is wildly different and can’t be easily refactored into separate functions.
  • You need to evaluate complex conditions (e.g., ranges, comparisons, multiple variables).

But for command handling, routing, dispatching, or simple control flows, it’s perfect.


Final Thoughts

Many developers write Python as if it’s JavaScript, Java, or C++. But Python has features that make it uniquely expressive — and dictionary-based dispatching is one of them.

If you find yourself writing repetitive if-elif-else chains to map strings or enums to behavior, give this pattern a try.

You’ll write less code, make fewer mistakes, and look more like a Python pro.


Enjoyed this trick?
Follow me for more practical Python insights that help you write cleaner, smarter code — every single day.

Photo by Krystal Ng on Unsplash