pkdkk
pkdkk

Reputation: 3963

python function call with variable

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?

Upvotes: 21

Views: 99961

Answers (4)

Tangy_leprechaun
Tangy_leprechaun

Reputation: 1

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]()

Upvotes: -2

Surya
Surya

Reputation: 84

def test():
    print 'test'

def test2():
    print 'test2'

assign_list=[test,test2]

for i in assign_list:
    i()

Upvotes: 0

chrisaycock
chrisaycock

Reputation: 37930

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.

Upvotes: 9

John Kugelman
John Kugelman

Reputation: 361575

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()

Upvotes: 42

Related Questions