Darren Ryan
Darren Ryan

Reputation: 21

python - call a function from a list item

I want to call a function named in the dictionary depending on the key called.

Example:

start_options = {'left': 'octopus', 'right': 'lion', 'small': 'pit', 'small door': 'pit'}

choice = raw_input("What do you want to do? ").lower()
        if choice in dictionary:
            print "found: " + choice, start_options[choice]
            print "You chose " + choice
            #code here will call function

def octopus():
    #do something

Upvotes: 1

Views: 71

Answers (1)

Random Davis
Random Davis

Reputation: 6857

If you define the functions beforehand, you can then refer to them directly in your dictionary as opposed to string representations:

def yada():
    print("Yada!")

def blah():
    print("Blah!")

start_options = {'test1': yada, 'test2': blah}
start_options['test1']()

Running this code produces:

Yada!

Upvotes: 2

Related Questions