Source From Here
Question
I'd like to call a function in python using a dictionary. Here is some code:
This prints
{'param': 'test'} but I'd like it to just print test. I'd like it to work similarly for more parameters:
Is this possible?
How-To
A few extra details that might be helpful to know (questions I had after reading this and went and tested):
Let's consider a function as example:
Number 1:
The function can have parameters that are not included in the dictionary
Number 2:
You can not override a parameter that is already in the dictionary
Question
I'd like to call a function in python using a dictionary. Here is some code:
- d = dict(param='test')
- def f(param):
- print param
- f(d)
- d = dict(p1=1, p2=2)
- def f2(p1,p2):
- print p1, p2
- f2(d)
How-To
A few extra details that might be helpful to know (questions I had after reading this and went and tested):
Let's consider a function as example:
- def mytest(a=4, b=2):
- print a, b
- In [2]: mydict = {'a': 100}
- In [3]: mytest(**mydict)
- a=100; b=2
- In [4]: mydict = {'a': 100, 'b': 200}
- In [5]: mytest(a=3, **mydict)
- ---------------------------------------------------------------------------
- TypeError Traceback (most recent call last)
5 -2fa5de36a628> in
- In [6]: mydict = {'a': 100, 'b': 200, 'c': 300}
- In [7]: mytest(**mydict)
- ---------------------------------------------------------------------------
- TypeError Traceback (most recent call last)
7 -ba7ed7e145e9> in
沒有留言:
張貼留言