2

I have a script which needs to iterate through thousands of various different, but simple options.

I can use if...elif to iterate through them, but am wondering if there is a faster / better option than thousands of elifs. For example

if something == 'a':
    do_something_a
elif something == 'b':
    do_something_b
elif something == 'c':
    do_something_c
elif something == 'd':
    do_something_d
...
A thousand more elifs
...
else:
    do_something_else

The thing I will be doing will usually be running a function of some kind.

4
  • It depends on where something comes from. Is it user input of some kind?
    – melpomene
    Sep 12, 2018 at 10:38
  • It would be a variable value, generally taken from a column in a database which I am iterating through.
    – Mike de H
    Sep 12, 2018 at 10:39
  • You can try using a dictionary...
    – Rakesh
    Sep 12, 2018 at 10:40
  • sounds like you could do this with a dict
    – Zinki
    Sep 12, 2018 at 10:40

3 Answers 3

4

you can use a dictionary to control mutliple possible logical paths:

def follow_process_a():
   print('following a')

def follow_process_b():
   print('following b')

keyword_function_mapper = 
{'a' : follow_process_a ,
 'b' : follow_process_b,                     
}

current_keyword = 'a'
run_method = keyword_function_mapper[current_keyword]
run_method()
2
  • Exactly what I needed. Thanks!
    – Mike de H
    Sep 12, 2018 at 10:48
  • you are welcome! If you want you can also mark this answer as accepted answer if it was what you were looking for.
    – matyas
    Sep 12, 2018 at 10:50
1

you can use a dictionary for that in this way:

def do_something_a():
    print 1

def do_something_b():
    print 2

dict = {'a': do_something_a, 'b': do_something_b}
dict.get(something)()
2
  • thank you, I fixed ; I expected that do_something_a() function is already exist. so this code will call it if something == a
    – Dmytro Huz
    Sep 12, 2018 at 11:04
  • @melpomene thank you that showed me that. you are absolutely right. I fixed it in my answer.
    – Dmytro Huz
    Sep 12, 2018 at 11:11
0

What I would recommend is to create a dictionary which maps the somethings to their respective function. Then you can apply this dictionary to the data.

More information: https://jaxenter.com/implement-switch-case-statement-python-138315.html (Dictionary Mapping)

Not the answer you're looking for? Browse other questions tagged or ask your own question.