21
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?
1

4 Answers 4

42

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()
Sign up to request clarification or add additional context in comments.

Comments

9

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.

4 Comments

Oof, not sure why you'd ever use this over the "function objects as keys themselves" method. If anything, you may be introspecting using something like hasattr, but never ever eval
@Daniel I didn't say it was pretty! :D
This works, but eval() has a lot of overhead to use it just calling a function. There's other better, way more "Pythonic" ways...
... like, for example, looking up the name in globals() and/or locals() perhaps? :)
0
def test():
    print 'test'

def test2():
    print 'test2'

assign_list=[test,test2]

for i in assign_list:
    i()

2 Comments

in assign_list test,test2 give to direct way i.e [test,test2]
for i in assign_list: this next line i()
-2
def test():
    print 'test'

def test2():
    print 'test2'

func_dict = {
    "test":test,
    "test2":test2
}


test = {'test':'blabla','test2':'blabla2'}
for key, val in test.items():
    func_dict[key]()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.