程式扎記: [ Python 常見問題 ] How to pass dictionary items as function arguments in python?

標籤

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"

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!