Switch statements in Python
7th May 2004
Python doesn’t support a native switch statement. I’ve found myself using the following coding idiom instead recently which seems to work pretty well:
{'option1': function1,
'option2': function2,
'option3': function3,
'option4': function4}[value]()
This works with lambdas as well, for inline calculations. Here’s a switch statement that assigns to a variable in PHP:
switch ($value) {
case 'a':
$result = $x * 5;
break;
case 'b':
$result = $x + 7;
break;
case 'c':
$result = $x - 2;
break;
}
And here’s the equivalent code in Python:
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
More recent articles
- Qwen2.5-Coder-32B is an LLM that can code well that runs on my Mac - 12th November 2024
- Visualizing local election results with Datasette, Observable and MapLibre GL - 9th November 2024
- Project: VERDAD - tracking misinformation in radio broadcasts using Gemini 1.5 - 7th November 2024