avatarKhuyen Tran

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4141

Abstract

he price for fish is 8'</span></pre></div><div id="d0b8"><pre>>>> <span class="hljs-function"><span class="hljs-title">find_price</span>(<span class="hljs-string">'cauliflower'</span>)</span> <span class="hljs-string">'The price for cauliflower is not available'</span></pre></div><p id="b851">Neat!</p><h1 id="3548">But Can I Use Dict with the Function that does not Involve with Dictionaries?</h1><p id="ec2e">Good question. Let’s tackle an example that completely does not involve a dictionary.</p><p id="a573">Imagine you want to create a function that returns a value for operation between 2 numbers. So this is what you come up with:</p><div id="f37e"><pre>def operations(<span class="hljs-keyword">operator</span>, x, y): <span class="hljs-keyword">if</span> <span class="hljs-keyword">operator</span> == <span class="hljs-string">'add'</span>: <span class="hljs-keyword">return</span> x + y elif <span class="hljs-keyword">operator</span> == <span class="hljs-string">'sub'</span>: <span class="hljs-keyword">return</span> x - y elif <span class="hljs-keyword">operator</span> == <span class="hljs-string">'mul'</span>: <span class="hljs-keyword">return</span> x * y elif <span class="hljs-keyword">operator</span> == <span class="hljs-string">'div'</span>: <span class="hljs-keyword">return</span> x / y</pre></div><div id="ebd2"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python">operations(<span class="hljs-string">'mul'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">8</span>)</span> 16</pre></div><p id="bb45">You can utilize dictionaries and <code>get()</code> method to get a more elegant code:</p><div id="33d1"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">operations</span>(<span class="hljs-params">operator, x, y</span>): <span class="hljs-keyword">return</span> { <span class="hljs-string">'add'</span>: <span class="hljs-keyword">lambda</span>: x+y, <span class="hljs-string">'sub'</span>: <span class="hljs-keyword">lambda</span>: x-y, <span class="hljs-string">'mul'</span>: <span class="hljs-keyword">lambda</span>: x*y, <span class="hljs-string">'div'</span>: <span class="hljs-keyword">lambda</span>: x/y, }.get(operator, <span class="hljs-keyword">lambda</span>: <span class="hljs-string">'Not a valid operation'</span>)()</pre></div><p id="5f92">Names of the operator become the keys and <code>lambda</code> efficiently condense the functions into the values of the dictionaries. <code>get()</code> returns a default value when no key is found. Let’s check our function:</p><div id="3264"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python">operations(<span class="hljs-string">'mul'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">8</span>)</span> 16 <span class="hljs-meta prompt_">>>></span> <span class="language-python">operations(<span class="hljs-string">'unknown'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">8</span>)</span> 'Not a valid operation'</pre></div><p id="a4d6">Great! It works like how we want.</p><h1 id="8f5a">So Should I Switch If-Else Statements to Dictionaries?</h1><p id="990c">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 <code>operations()</code> , it creates a temporary dictionary and lambdas for the opcode to loopup. This will slow down the performance of the code.</p><p id="7ce3">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.</p><p id="5a4a">Feel free to fork and play with the code for this article in <a href="https://github.com/khuyentran1401/Data-science/blob/master/python/dictionary_ifelse.ipynb">this

Options

Github repo</a>.</p><p id="f0bc">I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on <a href="https://www.linkedin.com/in/khuyen-tran-1401/">LinkedIn</a> and <a href="https://twitter.com/KhuyenTran16">Twitter</a>.</p><p id="be83">Star <a href="https://github.com/khuyentran1401/Data-science">this repo</a> 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:</p><div id="1a72" class="link-block"> <a href="https://towardsdatascience.com/timing-the-performance-to-choose-the-right-python-object-for-your-data-science-project-670db6f11b8e"> <div> <div> <h2>Timing for Efficient Python Code</h2> <div><h3>How to compare the performance between list, set and other methods</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Z06kusmgS5pPESFA)"></div> </div> </div> </a> </div><div id="d178" class="link-block"> <a href="https://towardsdatascience.com/maximize-your-productivity-with-python-6110004b45f7"> <div> <div> <h2>Maximize your Productivity with Python</h2> <div><h3>You create a to-do list to be productive but end up wasting your time on non-important tasks. What if you could create…</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*_rxIYhMJtDFAMu3YaXWxQQ.png)"></div> </div> </div> </a> </div><div id="ac45" class="link-block"> <a href="https://towardsdatascience.com/how-to-use-lambda-for-efficient-python-code-ff950dc8d259"> <div> <div> <h2>How to Use Lambda for Efficient Python Code</h2> <div><h3>Tricks to lambda to sort tuples and create sophisticated functions for your creative data science ideas</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*rH6hkj4X3N8xeOph5Su58A.jpeg)"></div> </div> </div> </a> </div><div id="42b3" class="link-block"> <a href="https://towardsdatascience.com/cython-a-speed-up-tool-for-your-python-function-9bab64364bfd"> <div> <div> <h2>Cython-A Speed-Up Tool for your Python Function</h2> <div><h3>When tweaking your algorithm gives small improvements, you may want to get an additional speed up with Cython, a…</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*9s44Iac6o6QYjiMt.png)"></div> </div> </div> </a> </div><div id="48cc" class="link-block"> <a href="https://readmedium.com/boost-your-efficiency-with-specialized-dictionary-implementations-7799ec97d14f"> <div> <div> <h2>Boost Your Efficiency With Specialized Dictionary Implementations</h2> <div><h3>Create dictionaries with ordered and read-only items, returning default values for non-existent keys, and much more</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*_gV8Lrm1jMND6Sie)"></div> </div> </div> </a> </div><h1 id="f79f">Reference</h1><p id="be7f">Bader, Dan. “Python Tricks.” 2017</p></article></body>

Dictionary as an Alternative to If-Else

Use Dictionaries to Create a Cleaner Code of If-Else Function

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 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.

Image by Gerd Altmann from Pixabay

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 = {
'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!

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):
    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.

So Should I Switch If-Else Statements to Dictionaries?

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:

Reference

Bader, Dan. “Python Tricks.” 2017

Python3
Python
Programming
Dictionary
If Else
Recommended from ReadMedium