How to Use Dictionaries as an Alternative to If-Else

Create a Cleaner Code of If-Else Functions with Dictionaries

Motivation

You may have been frequently working with Python’s dictionaries. But have you unlocked the full capacity of the dictionary to create a more efficient code? If you didn’t know you can create an ordered dictionary, group multiple dictionaries into a single mapping, create a read-only dictionary, you could found out more here.

This article will focus on how to use Python’s dictionaries as an alternative to if-else statements

Cut the If-Else Statements with the Bonus of Default Values

Imagine we have the price list of items in the grocery store:

price_list = {<br>'fish': 8,<br>'beef': 7,<br>'broccoli': 3,<br>}

We want to print the price of the item but anticipate that not every item is in the price_list.So we decide to create a function:

def find_price(item):<br>    if item in price_list:<br>        return 'The price for {} is {}'.format(item, price_list[item])<br>    else:<br>        return 'The price for {} is not available'.format(item)
&gt;&gt;&gt; find_price('fish')<br>'The price for fish is 8'
&gt;&gt;&gt; find_price('cauliflower')<br>'The price for cauliflower is not available'

Smart. The if-else statement does exactly what we want it to do: return another value when the item is not available. But we query the dictionary twice and use two statements just to return almost the same thing. Can we do better? Is there a way that if the item is not in the list, a default value will be returned? Fortunately, there is a way to do that with Python’s dictionaries method called get()

def find_price(item):<br>    return 'The price for {} is {}'.format(item, price_list.get(<br>        item, 'not available'))

.get() looks up a key and returns default value with the non-existent key. The code definitely looks shorter, but does it performs like how we want?

&gt;&gt;&gt; find_price('fish')<br>'The price for fish is 8'
&gt;&gt;&gt; find_price('cauliflower')<br>'The price for cauliflower is not available'

Neat! 

But Can I Use Dict with the Function that does not Involve with Dictionaries?

Good question. Let’s tackle an example that completely does not involve a dictionary.

Imagine you want to create a function that returns a value for operation between 2 numbers. So this is what you come up with:

def operations(operator, x, y):<br>    if operator == 'add':<br>        return x + y<br>    elif operator == 'sub':<br>        return x - y<br>    elif operator == 'mul':<br>        return x * y<br>    elif operator == 'div':<br>        return x / y
&gt;&gt;&gt; operations('mul', 2, 8)<br>16

This is where it is even more impressive to see a dictionary :

def operations(operator, x, y):<br>    return {<br>        'add': lambda: x+y,<br>        'sub': lambda: x-y,<br>        'mul': lambda: x*y,<br>        'div': lambda: x/y,<br>    }.get(operator, lambda: 'Not a valid operation')()

Names of the operator become the keys and lambda efficiently condense the functions into the values of the dictionaries. get() returns a default value when no key is found. Let’s check our function:

&gt;&gt;&gt; operations('mul', 2, 8)<br>16<br>&gt;&gt;&gt; operations('unknown', 2, 8)<br>'Not a valid operation'

Conclusion

Congratulation! You learn how to use dictionaries as alternatives to if-else statements. So when can you apply these tricks? If you recognize that your if-else statements are repetitive, it may be a good idea to consider using dictionaries. This technique certainly won’t apply in every situation, but it will be beneficial to have another technique in your toolbox to choose from.

I like to write about basic mathematical and programming concepts and play with different data science tools. Check out my blog to get updated about my latest articles. You could also connect with me on LinkedIn and Twitter.

read original article here