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.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Mike de H
  • 599
  • 2
  • 6
  • 13

3 Answers3

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()
matyas
  • 2,696
  • 23
  • 29
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)()
Dmytro Huz
  • 1,514
  • 2
  • 14
  • 22
  • 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 '18 at 11:04
  • @melpomene thank you that showed me that. you are absolutely right. I fixed it in my answer. – Dmytro Huz Sep 12 '18 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)