def test():
print 'test'
def test2():
print 'test2'
test = {'test':'blabla','test2':'blabla2'}
for key, val in test.items():
key() # Here i want to call the function with the key name, how can i do so?
Run Code Online (Sandbox Code Playgroud)
Joh*_*ica 24
您可以将实际的函数对象本身用作键,而不是函数的名称.函数是Python中的第一类对象,因此直接使用它们比使用它们的名称更清晰,更优雅.
test = {test:'blabla', test2:'blabla2'}
for key, val in test.items():
key()
Run Code Online (Sandbox Code Playgroud)
约翰有一个很好的解决方案。这是另一种方法,使用eval():
def test():
print 'test'
def test2():
print 'test2'
mydict = {'test':'blabla','test2':'blabla2'}
for key, val in mydict.items():
eval(key+'()')
Run Code Online (Sandbox Code Playgroud)
请注意,我更改了字典的名称,以防止与test()函数名称发生冲突。