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. 
                A double asterisk ** is used for unpacking a dictionary and passing it as keyword arguments during the function call. Example 1: Unpacking dictionary during the function call. mul(**d )→ It will unpack the elements in the dictionary and pass it as keyword arguments during the function call.
Unpacking Dictionaries With the ** Operator In the context of unpacking in Python, the ** operator is called the dictionary unpacking operator. The use of this operator was extended by PEP 448. Now, we can use it in function calls, in comprehensions and generator expressions, and in displays.
Passing Dictionary as kwargs “ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.
Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter. Always place the **kwargs parameter at the end of the parameter list, or you'll get an error.
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() 
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With