Improve Your Python Code With This Quick Else-if Tip

Improve Your Python Code With This Quick Else-if Tip
Photo by Radowan Nakif Rehan / Unsplash

Today I want to share with you a small tip that I regularly use to prevent having to write multiple else-if statements within my code. You may now be asking,

what's wrong with writing multiple else-if statements?

Well, to be fair, nothing. However, I will show you an alternative that will improve code readability and also help you reduce your code a bit.

So, let's look at an example. Let's say we have the following function. That will return us the vendor for a platform based on the input provided.

def get_vendor(platform):
    if platform == "asr":
        return "cisco"
    elif platform == "csr":
        return "cisco"
    elif platform == "qfx":
        return "juniper"
    elif platform == "mx":
        return "juniper"
    else:
        return "no platform found"

>>> get_vendor(platform="csr")
cisco

This code is Ok, but there is another way. Instead of using multiple else if statements, create a dictionary and perform a lookup against the dictionary. Like so:

def get_vendor(platform):
    platform_to_vendor = {
        "asr": "cisco",
        "csr": "cisco",
        "qfx": "juniper",
        "mx": "juniper",
    }
    return platform_to_vendor.get(platform, "no platform found")

>>> get_vendor(platform="csr")
cisco

And well, that's it; as you can see, the code is cleaner and easier to read. Good stuff!

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!