Dictionary as an Alternative to If-Else

It is common to use the else statement to cover the cases that the if statement doesn’t cover. For example, in the code above, we use the else statement when the item is not on the price list. 

This method works, but we query the dictionary twice and use two statements just to return almost the same thing. We can reduce the redundancy in the code with the get method.

get looks up a key and returns the default value when a key doesn’t exist.

My previous tips on Python dictionary.

Scroll to Top