Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Dictionary as an Alternative to If-Else

Table of Contents

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran