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"

沒有留言:

張貼留言

[JS 文章收集] 用 Node.js 學 JavaScript 語言(1)簡介與安裝

Source From  Here   簡介   Node.js  是 Ryan Dahl 基於 Google 的 V8 引擎於 2009 年釋出的一個 JavaScript 開發平台,主要聚焦於 Web 程式的開發,通常用被來寫網站。但是,要開發網站就勢必要把「 HTML,...