17
votes
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?
4
Oh year .. i see ,, :), just a fast test code ;) - pkdkk

4 Answers

31
votes

You could use the actual function objects themselves as keys, rather than the names of the functions. Functions are first class objects in Python, so it's cleaner and more elegant to use them directly rather than their names.

test = {test:'blabla', test2:'blabla2'}

for key, val in test.items():
    key()
11
votes

If what you want to know is "How to call a function when you have it's name in a string", here are some good answers - Calling a function of a module from a string with the function's name in Python

3
votes

John has a good solution. Here's another way, using eval():

def test():
        print 'test'

def test2():
        print 'test2'

mydict = {'test':'blabla','test2':'blabla2'}
for key, val in mydict.items():
        eval(key+'()')

Note that I changed the name of the dictionary to prevent a clash with the name of the test() function.

-1
votes
def test():
    print 'test'

def test2():
    print 'test2'

assign_list=[test,test2]

for i in assign_list:
    i()