Dictionary as an Alternative to If-Else | by Khuyen Tran | Towards Data Science

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 how to 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.
Imagine we have the price list of items in the grocery store:
price_list = {'fish': 8,'beef': 7,'broccoli': 3,}
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):    if item in price_list:        return 'The price for {} is {}'.format(item, price_list[item])    else:        return 'The price for {} is not available'.format(item)>>> find_price('fish')'The price for fish is 8'>>> find_price('cauliflower')'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):    return 'The price for {} is {}'.format(item, price_list.get(        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?
>>> find_price('fish')'The price for fish is 8'>>> find_price('cauliflower')'The price for cauliflower is not available'
Neat!
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):    if operator == 'add':        return x + y    elif operator == 'sub':        return x - y    elif operator == 'mul':        return x * y    elif operator == 'div':        return x / y>>> operations('mul', 2, 8)16
You can utilize dictionaries and get() method to get a more elegant code:
def operations(operator, x, y):    return {        'add': lambda: x+y,        'sub': lambda: x-y,        'mul': lambda: x*y,        'div': lambda: x/y,    }.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:
>>> operations('mul', 2, 8)16>>> operations('unknown', 2, 8)'Not a valid operation'
Great! It works like how we want.
The alternative makes the code look cleaner. But if we want to use dictionary, we should consider the downsides of this switch. Every time we call operations() , it creates a temporary dictionary and lambdas for the opcode to loopup. This will slow down the performance of the code.
Thus, if we want to use dictionaries, we should consider creating the dictionary once before the function call. This act prevents the code from recreating the dictionary every time we lookup. This technique certainly won’t apply in every situation, but it will be beneficial to have another technique in your toolbox to choose from.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
medium.com
Bader, Dan. “Python Tricks.” 2017