Search code examples
pythondictionaryargument-unpacking

Python keyword arguments unpack and return dictionary


I have a function definition as below and I am passing keyword arguments. How do I get to return a dictionary with the same name as the keyword arguments?

Manually I can do:

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
    }

But I don't want to do that. Is there any way that I can make this work without actually typing the dict?

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

Solution

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