Long if else ladder vs dictionary

Posted by Afsal on 23-Feb-2024

Hi Pythonistas!

Today in this post is a simple technique that can be used to make code smaller and also faster. In most of the cases we replace the long if else ladder with a dictionary. Let us explain with an example.

Code

def using_long_if_else_ladder(9):
    if number == 1:
        return "One"
    elif number == 2:
        return "Two"
    elif number == 3:
        return "Three"
    elif number == 4:
        return "Four"
    elif number == 5:
        return "Five"
    elif number == 6:
        return "Six"
    elif number == 7:
        return "Seven"
    elif number == 8:
        return "Eigth"
    elif number == 9:
        return "Nine"


MAPPING = {
    1: "One",
    2: "Two",
    3: "Three",
    4: 'Four',
    5: 'Five',
    6: 'Six',
    7: 'Seven',
    8: 'Eigth',
    9: 'Nine'
}

def using_dict(number ):
    return MAPPING[number]

In above example we can see that code is very simpler and get the same output

Let us check the performance change. For that i have made a small change in function instead of passing i have hard coded inside the function

Code

import timeit

def using_long_if_else_ladder():
    number = 9
    if number == 1:
        return "One"
    elif number == 2:
        return "Two"
    elif number == 3:
        return "Three"
    elif number == 4:
        return "Four"
    elif number == 5:
        return "Five"
    elif number == 6:
        return "Six"
    elif number == 7:
        return "Seven"
    elif number == 8:
        return "Eigth"
    elif number == 9:
        return "Nine"

MAPPING = {
    1: "One",
    2: "Two",
    3: "Three",
    4: 'Four',
    5: 'Five',
    6: 'Six',
    7: 'Seven',
    8: 'Eigth',
    9: 'Nine'
}

def using_dict():
    number = 9
    return MAPPING[number]


time_taken_for_long_if = timeit.timeit(using_long_if_else_ladder, number=1000_000)
print("Time taken for long if: ", time_taken_for_long_if)

time_taken_for_using_dict = timeit.timeit(using_dict, number=1000_000)
time_taken_for_using_dict = timeit.timeit(using_dict, number=1000_000)

Output

Time taken for long if:  0.20214992899855133

Time taken for using_dict:  0.06510571000399068

We can see a big change in performance between these two. Whenever you see a long if check where we can replace with dict.

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in