dictionary - python關鍵字參數解包,並返回字典

我有一個如下的函數定義,我傳遞關鍵字參數,如何返回與關鍵字參數同名的字典?

手動我可以執行以下操作:


def generate_student_dict(first_name=None, last_name=None , birthday=None, gender =None):


 return {


 'first_name': first_name,


 'last_name': last_name,


 'birthday': birthday,


 'gender': gender


 }



但我不想那樣做,有沒有辦法讓我在不實際輸入dict的情況下工作?


 def generate_student_dict(self, first_name=None, last_name=None, birthday=None, gender=None):


 return # Packed value from keyword argument.



时间:

如果這種方法適合你,請使用 kwargs(請參見理解kwargs在python),如下面的代碼片段所示:


def generate_student_dict(self, **kwargs): 


 return kwargs



否則,可以在函數start處使用built-in locals()創建params的副本,並返回該副本:


def generate_student_dict(first_name=None, last_name=None , birthday=None, gender =None):


 # It's important to copy locals in first line of code (see @MuhammadTahir comment).


 args_passed = locals().copy()


 # some code


 return args_passed



generate_student_dict()



如果不想通過**kwargs,你可以簡單地返回locals


def generate_student_dict(first_name=None, last_name=None, 


 birthday=None, gender=None):


 return locals()



請注意,如果將self作為參數傳遞,則需要從結果中移除。

**kwargs中獲取關鍵字參數


def generate_student_dict(self, **kwargs):


 # use it like


 # kwargs.get('first_name')


 # kwargs.get('last_name')


 # kwargs.get('birthday')


 # kwargs.get('gender')


 return kwargs



如果希望將更新后的值作為字典返回

def generate_student_dict(first_name=None, last_name=None , birthday=None, gender =None):


 main_args = locals().copy()


 first_name = 'first'


 last_name = 'last'


 birthday = '20 jan 1993'


 newvar = 100


 new_args = locals().copy()


 updated_args = {}



 for k,v in new_args.items():


 if k in main_args.keys():


 updated_args[k] = v


 return updated_args



dict = generate_student_dict()


print(dict) #{'first_name': 'first', 'last_name': 'last', 'birthday': '20 jan 1993', 'gender': None}



如果要將iniital值作為字典返回

def generate_student_dict_1(first_name=None, last_name=None , birthday=None, gender =None):


 args = locals()


 first_name = 'first'


 last_name = 'last'


 birthday = '20 jan 1993'


 newvar = 100


 return args



dict = generate_student_dict_1()


print(dict) #{'first_name': None, 'last_name': None, 'birthday': None, 'gender': None}



如果要包含所有更改包括在方法內部定義的額外變數

def generate_student_dict_2(first_name=None, last_name=None , birthday=None, gender =None):


 first_name = 'first'


 last_name = 'last'


 birthday = '20 jan 1993'


 newvar = 100


 args = locals()


 return args



dict = generate_student_dict_2()


print(dict) #{'first_name': 'first', 'last_name': 'last', 'birthday': '20 jan 1993', 'gender': None, 'newvar': 100}



...