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"
        return "no platform found"

>>> get_vendor(platform="csr")

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")

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

Ready to Master Network Automation? Start Your Journey Today!
Our membership provides:
  • Full deep-dive course library (inc. Batfish, pyATS, Netmiko)
  • Code repositories inc. full course code, scripts and examples
  • 24x7 multi-vendor labs (Arista, Cisco, Juniper)
  • Private online community
  • Live monthly tech sessions
  • Access to tech session library

Join Now ➜