2019年3月5日 星期二

[ Python 常見問題 ] Passing a dictionary to a function in python as keyword parameters

Source From Here 
Question 
I'd like to call a function in python using a dictionary. Here is some code: 
  1. d = dict(param='test')  
  2.   
  3. def f(param):  
  4.     print param  
  5.   
  6. f(d)  
This prints {'param': 'test'} but I'd like it to just print test. I'd like it to work similarly for more parameters: 
  1. d = dict(p1=1, p2=2)  
  2. def f2(p1,p2):  
  3.     print p1, p2  
  4. f2(d)  
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): 
1. The function can have parameters that are not included in the dictionary 
2. You can not override a parameter that is already in the dictionary 
3. The dictionary can not have parameters that aren't in the function.

Let's consider a function as example: 
  1. def mytest(a=4, b=2):  
  2.     print a, b  
Number 1: The function can have parameters that are not included in the dictionary 
  1. In [2]: mydict = {'a': 100}  
  2.   
  3. In [3]: mytest(**mydict)  
  4. a=100; b=2  
Number 2: You can not override a parameter that is already in the dictionary 
  1. In [4]: mydict = {'a': 100, 'b': 200}  
  2.   
  3. In [5]: mytest(a=3, **mydict)  
  4. ---------------------------------------------------------------------------  
  5. TypeError                                 Traceback (most recent call last)  
  6. 5-2fa5de36a628> in   
  • ----> 1 mytest(a=3, **mydict)  
  •   
  • TypeError: mytest() got multiple values for keyword argument 'a'  
  • Number 3: The dictionary can not have parameters that aren't in the function. 
    1. In [6]: mydict = {'a': 100, 'b': 200, 'c': 300}  
    2.   
    3. In [7]: mytest(**mydict)  
    4. ---------------------------------------------------------------------------  
    5. TypeError                                 Traceback (most recent call last)  
    6. 7-ba7ed7e145e9> in   
  • ----> 1 mytest(**mydict)  
  •   
  • TypeError: mytest() got an unexpected keyword argument 'c'  


  • 沒有留言:

    張貼留言

    [Git 常見問題] error: The following untracked working tree files would be overwritten by merge

      Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...