Using Python Dictionaries as a Potential Alternative to IF Conditions
A lesser-known usage of dictionaries in Python.
Dictionaries are mainly used as a data structure in Python for maintaining key-value pairs.
But unknown to many, there’s another special use case of dictionaries — using them as a potential alternative to IF conditions.
For instance, consider the code snippet below. Here, corresponding to an input value, we invoke a specific function.
The traditional way requires you to hard-code every case (𝐢𝐟_𝐞𝐥𝐬𝐞.𝐩𝐲).
But with a dictionary (𝐝𝐢𝐜𝐭.𝐩𝐲), you can directly retrieve the corresponding function by providing it with the key.
Isn’t that cool, elegant, and neat?
👉 Over to you: What other lesser-known Python hacks are you aware of?
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (550+ pages) with 320+ tips.
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.
Thanks for reading!
Whenever you’re ready, here are a couple of more ways I can help you:
Get the full experience of the Daily Dose of Data Science. Every week, receive two deep dives that:
Make you fundamentally strong at data science and statistics.
Help you approach data science problems with intuition.
Teach you concepts that are highly overlooked or misinterpreted.
Promote to 33,000 subscribers by sponsoring this newsletter.
👉 Tell the world what makes this newsletter special for you by leaving a review here :)
👉 If you love reading this newsletter, feel free to share it with friends!