6

I have a Python program asking the user for input like a shell, and if I detect some specific keywords I want to go inside some specific functions.

The thing is that I would like to avoid doing a lot of if and else if. Usually in C to avoid this situation I use a function pointer array that I travel with a while and use strcmp to check the input.

I would like to know how to do that in Python if it is even possible.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Roger
  • 657
  • 5
  • 18
  • Are you looking for something like http://stackoverflow.com/q/60208/3001761? For those of us not *au fait* with C, it might be helpful to provide more information about what you're talking about. – jonrsharpe May 13 '15 at 21:02
  • 1
    Maybe you want a dictionary mapping string keys to functions? I don't understand why you would need to use a while loop in C. – Shashank May 13 '15 at 21:05
  • @Shashank you could use a while loop if the array of function pointers was NULL terminated. – Paul Rooney May 13 '15 at 21:07
  • Yes, a dictionary is what I need apparently, thank you! (and yes I use a NULL terminated array for my loop in C) – Roger May 13 '15 at 21:10

1 Answers1

9

In Python you use a dictionary.

Example:

keyword2func = {
    "word1": function_word1,
    "word2": function_word2,
}

word = input("")
keyword2func[word]()
jesterjunk
  • 2,342
  • 22
  • 18
Daniel
  • 42,087
  • 4
  • 55
  • 81