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?
In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object. This variable can now be used anywhere inside or outside any function.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With