Python Gem #19: Look up table > if chain

What should be a really simple function has turned into a fifty-line gargantuan that’s too hard to read properly because of the sheer number of lines. The culprit; a seriously long if-elsif-else chain. But not to fear; there’s a better way!

You can use dict as look up tables; it makes for much easier reading code and as you’re able to put more then one key-value pair on a line you can reduce your total line usage drastically. Simply follow the following procedure;

if <check_value == value_needed1>: 
return <value1>
elif <check_value == value_needed2>:
return <value2>
elif <check_value == value_needed3>:
return <value3>
... repeat for a bajillion lines ...
# 1. Create a dict 
values = { }
# 2. For each checked value and return value, create a pair. 
values = {
"<value_needed1>": "<value1>", "<value_needed2>": "<value2>",
"<value_needed3>": "<value3>", "<value_needed4>": "<value4>",
... more ...
#3. replace all those return values with
return values[check_value]


This is a daily series called Python Gems. Each short posts covers a detail, feature, design pattern or application of the python language and the surrounding libraries that you can use to increase your codes readability while decreasing its length.