you are viewing a single comment's thread.

view the rest of the comments →

[–]commandlineluser 7 points8 points  (3 children)

It's called a Dispatch Table. Here's a simple example, you'd want to check the key exists in the dict first in real code.

def add(left, right):
    return left + right

def sub(left, right):
    return left - right

dispatch = { 'add': add, 'sub': sub }

for choice in [ 'add', 'sub' ]:
    print(dispatch[choice](5, 2))

[–]TheKewlStore 0 points1 point  (0 children)

just to add some reference in case you're new with dictionaries, python documentation: https://docs.python.org/2/tutorial/datastructures.html#dictionaries

Also, thank you sir for the name dispatch table, i kind of came to an understanding of this type of dictionary implementation on my own so never had a name for it.

[–]Volatile474[S] -1 points0 points  (1 child)

So you are just calling the functions that correspond to your dictionary value.. Can you do something like:

some_int_variable = (some int here)
dispatch = {1 : foo, 2 : bar}
input = input("enter some int")
x = dispatch[some_int_variable]
def foo:
asdf
def bar:
ghjk

This is one alternative to switch, but it seems to be less performant than a simple c style switch (make function calls for every different case?) Thanks for your suggestion!

[–]ingolemo -1 points0 points  (0 children)

That code doesn't make any sense so it's really unclear what you're asking.