Replace If-Else Chains with Dictionary Mapping in Python

If you tired of Using long complex if-else Chains in Python. Stop it right now. !! Start leveraging Dictionary Mapping Instead: ______________ For example: Let's suppose a messy data column as values like - "mgr", "manager", "Manager", "Sr Manager", "MGR". Old technique ( Lengthy to write & difficult to manage in longer run)- if x == "mgr":   role = "Manager" elif x == "Manager":   role = "Manager" elif x == "MGR":   role = "Manager" ... New technique ( Dict Mapping) - 1. First create a mapping: mapping = {  "mgr": "Manager",   "manager": "Manager",   "sr manager": "Senior Manager" } 2. Map the correct role: role = mapping.get(x.lower().strip(), "Unknown") Done!! _______________ This small implementation can save efforts & complexity of the code. #python #coding_ideas #data #dataengineering #datascientist #dataanlayst #python_learning

To view or add a comment, sign in

Explore content categories