If you are doing simple task which involves just one statement, instead of using if-elif in Python, you may implement switch statements more elegantly using dictionary.
>>> switch('a') # 'a' exists as key
'value_a'
>>> switch('z') # 'z' doesn't exists as key
'value_default'
Above function will return "value" function corresponding to "key". If "key" not found in dictionary, it will return value as "default_value", just like default in switch statements.
That's not really a switch statement, but more of a dictionary abstraction. In a real switch, you can run code based on the value. If I were to modify your snippet, I'd have to get busy with functions and stuff.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
If you are doing simple task which involves just one statement, instead of using
if-elif
in Python, you may implement switch statements more elegantly using dictionary.For example:
Sample Run:
Above function will return "value" function corresponding to "key". If "key" not found in dictionary, it will return value as "default_value", just like default in
switch
statements.That's not really a switch statement, but more of a dictionary abstraction. In a real switch, you can run code based on the value. If I were to modify your snippet, I'd have to get busy with functions and stuff.