Replace if-else with dictionary python
Python dictionary comprehension is a method for transforming one dictionary into a new dictionary. Using an if-else in Python dict comprehension is one of the ways to create a new list. It works as a condition to filter out dictionary elements for a new dictionary. Simple example code adding conditionals to
Dictionary comprehension. Replace the value with ‘Even‘ if the value module is zero else replaced it with ‘Odd‘. Output: Do comment if you have any doubts or suggestions on this Python dictionary tutorial.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical. If statements are great tools, but as the number of branches grows, they quickly become unwieldy. In this article, we will explore two alternatives to if statements: Imagine you have an if statement like this one (assume the
Using match...case to simplify an if statement chainIn "match...case", we still need to tell Python what the different options are, and what to do in each case:
While this looks a bit better, there is still much of the
same duplication. Each conditional branch has the Overall, the length of the code block is the same. Plus the biggest problem of all remains: that as you add more options, the branching conditional will grow too. Use a dictionary to simplify a long if statementInstead of the log if-elif chain or a long match-case chain, you could store the user's options in a dictionary:
Then you could ask the user for which of the options (from the dictionary) they'd like to use:
With this, we can retrieve the function from the dictionary directly:
Since the dictionary maps strings to functions, the All that's left is to run We should also do some error checking, to make sure we don't try to run a function that doesn't exist if the user entered something that isn't one of the dictionary's keys.
You still need the one if statement just in case the user chooses something that doesn't have a key in the dictionary, but this is a single-branch if statement that won't grow over time. Another benefit is that you can easily tell the user which options are available to them by using the dictionary keys:
ConclusionIn this post we've seen two ways you can simplify if statements: by using "match...case" and by using dictionaries. If you want to learn more about Python, consider enrolling in our Complete Python Course which takes you from beginner all the way to advanced (including OOP, web development, async development, and much more!). We have a 30-day money-back guarantee, so you really have nothing to lose by giving it a try. We'd love to have you! Photo by Christin Hume on Unsplash |