Reputation: 175
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 ?
Upvotes: 0
Views: 97
Reputation: 107287
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 since it's usually easier to ask for forgiveness than permission, the try-except
method is more cleaner and Pythonic in this case, but instead of directly indexing you can also use dict.get()
which returns None
in case of missing the key. Then you can check if the result is None
, then just do pass
.
Upvotes: 2