Piduna Piduna - 4 months ago 16
Linux Question

Use switch case in python with special condition

i have this:

if you == 1:
one.put(argument)
elif you == 3:
pass
elif you == 4:
two.put(argument)
elif you == 5:
three.put(argument)
...
...
...
a lot of elif


I am trying to use dictionary:

settings = {
1: one
4: two,
5: three
...
...
...
other elemets of dict
}

if you in settings:
settings[you].put(argument)


Everything is ok, but i have no idea, how to add this in dictionary:

elif you == 3:
pass


How you think, what the better way to add
pass
statement to dictionary ?

Answer Source

First off, you don't need to check the existence of the item in setting when you're using a dictionary. The whole point of using a dictionary in this case is avoiding that check.

Secondly, If it's only 3 you can simply use an if condition:

if you == 3:
    pass
else:    
    settings[you].put(argument)

If there are more such items, you can use a try-except (without having them in your dictionary):

try:
    settings[you].put(argument)
except KeyError:
    pass

Note that it's usually easier to ask for forgiveness than permission the try-except method would be better in this case otherwise you can also use dict.get() instead of directly indexing and check if the result of the method is None just do pass.