DEV Community

Discussion on: What's a useful programming language feature or concept that a lot of languages don't have?

Collapse
 
moin18 profile image
Moinuddin Quadri

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:

def switch(key):
     return {
          'a': 'value_a',
          'b': 'value_b'
    }.get(key, 'value_default')

Sample Run:

>>> 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.

Collapse
 
tobiassn profile image
Tobias SN

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.