Python keyword arguments unpack and return dictionary

Get keyword arguments in **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

If that way is suitable for you, use kwargs (see Understanding kwargs in Python) as in code snippet below:

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

Otherwise, you can create a copy of params with built-in locals() at function start and return that copy:

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()

You can use locals() function. locals() updates and returns a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.


If you don't want to pass **kwargs, you can simply return locals:

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

Note that you want to remove self from the result if you pass it as an argument.