我想根据被调用的键调用字典中指定的函数。
示例:
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
答案 0 :(得分:2)
如果您事先定义了这些函数,那么您可以直接在字典中引用它们而不是字符串表示:
def yada():
print("Yada!")
def blah():
print("Blah!")
start_options = {'test1': yada, 'test2': blah}
start_options['test1']()
运行此代码会产生:
矢田!