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}



...