Python Functions and Double Asterisks ** Operator

In this section, we will learn about functions and double asterisks operator.

Note: we’re also assuming you’re familiar with the keyword arguments in Python.

Extracting and Gathering Keyword Arguments with Asterisk ** Operator

As mentioned in the function section, we can call a function and pass arguments to it using the name of parameters in that function!

For example:

def funcName(pOne, pTwo): 
    #body… 
funcName(pOne = 10, pTwo = 30)

Here, as you can see, we used the name of the parameters and passed arguments exactly to each parameter.

But sometimes a function might need to take an arbitrary number of keyword arguments which we couldn’t decide the exact number of arguments ahead of time when designing the function!

This is where we can use the double asterisks `**` operator! Using this operator, python allows us to create a parameter for a function that basically represents an empty dictionary.

Now a function that has such a parameter is capable of taking any random number of keyword-arguments. Basically, these arguments will be stored in that dictionary as a pair of key-value (The keyword argument becomes the key and the value we pass to that keyword becomes the value in the dictionary for the related key).

Python Gathering Keyword Arguments with Asterisk ** Operator Syntax

This is how we can create a dictionary parameter in a function:

def functionName(parameter1, parameterN, **dict)

Note that a function with dictionary parameter is still capable of having usual parameters as well. But the important note to remember is that the dictionary parameter should be positioned as the last parameter of the function.

For example, here the function has two simple parameters and one dictionary parameter.

Now, if we call the function with 4 keyword arguments, for example, then the first two parameters will get their values and the rest (the other two arguments) will become as the key-value pairs (elements) of the dictionary parameter.

Example: gathering Keyword arguments with ** operator

def details(firstName, lastName, **dict):
    print(f"The first name is: {firstName} and the last name is: {lastName}")
    print("Here are the rest of information:")
    for key,value in dict.items():
        print(f"{key}: {value}")


details("John","Doe",age = 1000, email = "[email protected]",address = "Mars", salary = "200,000,000,000")

Output:

The first name is: John and the last name is: Doe

Here are the rest of information:

age: 1000

email: [email protected]

address: Mars

salary: 200,000,000,000

Notes:

– Please check the `for` loop section if you’re not familiar with this loop.

– Also please check the `dictionary` section in order to learn about this object.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies