Piduna
Piduna

Reputation: 175

The best way to replace multiple if-statementes with a dictionary

I have a multiple condition:

if you == 1 or you == 2:
    one.put(argument)
elif you == 3:
    return None
elif you == 4:
    two.put(argument)
elif you == 5:
    three.put(argument)
elif you == 6:
    four.put(argument)
elif you == 7:
    five.put(argument)
elif you == 8:
    six.put(argument)
elif you == 9:
    seven.put(argument)
elif you == 10:
    eight.put(argument)
elif you == 11:
    nine.put(argument)
elif you == 12:
    ten.put(argument)

I want to change it to use a dictionary, but I get exceptions in:

if you == 1 or you == 2:
    one.put(argument)
elif you == 3:
    return None

What is the best way to do this?

Upvotes: 2

Views: 6379

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

I'd create a sink for the values you don't want:

class Sink:
    @staticmethod
    def put(object):
        pass

put_dict = {
    1: one, 2: one,
    3: Sink,
    4: two,  5: three,
    6: four, 7: five,
    8: six,  9: seven,
    10: eight, 11: nine,
    12: ten}

def function(you, argument)
    put_dict[you].put(argument)

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81664

This will work:

actions = {1: one.put,
           2: one.put,
           3: None,
           4: two.put,
           # ....
           }

action = actions.get(you)
if callable(action):  # guards against non existing "you"'s or if you == 3
    action(argument)

# can also do this:
# if action is not None:
    # action(argument)

# or that..
# try:
#     action(argument)
# except TypeError:  # if action is None we'll get an exception, NoneType isn't callable
#    pass

Upvotes: 6

Prune
Prune

Reputation: 77860

Store the varying part of your expression in a dictionary. I put 3 in there as well, just for completeness, and possible later use.

put_dict = {
    1: one, 2: one,
    3: None
    4: two,  5: three,
    6: four, 7: five,
    8: six,  9: seven,
    10: eight, 11: nine,
    12: ten
}

if you == 3:
    return None
else:
    put_dict[you].put(argument)  

Upvotes: 2

Related Questions