2016年10月12日 星期三

[ Python 常見問題 ] How to pass dictionary items as function arguments in python?

Source From Here 
Question 
As title. I have a function as below: 
  1. def my_function(first, last, age, middle=''):  
  2.      print "My name is %s %s (%s) and I am %d years old" % (first, last, middle, age)  
How do I pass data as dict into my_function (With key as argument name and value as argument value). For example: 
  1. data_dict = {"first":"Lee""last":"John""middle":"KC""age":18}  
How-To 
Check below usage: 
>>> data_dict = {"first":"Lee", "last":"John", "middle":"KC", "age":18}
>>> my_function(**data_dict)
My name is Lee John (KC) and I am 18 years old
>>> data_list = ["Lin", "Ken"]
>>> data_dict2 = {"age":33}
>>> my_function(*data_list, **data_dict2)
My name is Lin Ken () and I am 33 years old

More on how to use function in Python, please refer to "[Quick Python] 9. Functions"

沒有留言:

張貼留言

[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...