Python关键字参数解包并返回字典

时间:2016-02-04 10:00:39

标签: python dictionary argument-unpacking

我有一个函数定义如下,我传递的是关键字参数。如何返回与关键字参数同名的字典?

手动我可以做:

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
    }

但我不想这样做。有没有办法让我可以在不实际输入字典的情况下完成这项工作?

 def generate_student_dict(self, first_name=None, last_name=None, birthday=None, gender=None):
     return # Packed value from keyword argument.

5 个答案:

答案 0 :(得分:13)

如果这种方式适合您,请使用kwargs(请参阅Understanding kwargs in Python),如下面的代码段所示:

Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
Dim employees As IEnumerable(Of XElement) = xelement.Elements()
' Read the entire XML
For Each employee In employees
      Console.WriteLine(employee)
Next employee

否则,您可以在功能开始时创建built-in locals()的params副本,然后返回复制:

def generate_student_dict(self, **kwargs):            
     return kwargs

答案 1 :(得分:8)

如果您不想传递**kwargs,只需返回locals

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

请注意,如果将结果作为参数传递,则要从结果中删除self

答案 2 :(得分:3)

**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

答案 3 :(得分:1)

您可以使用locals()功能。 locals()更新并返回表示当前本地符号表的字典。 locals()在函数块中调用时会返回自由变量,但不会在类块中调用。

答案 4 :(得分:0)

如果您想将更新后的值作为字典返回

    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}

如果您想将初始值作为字典返回

    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}