In this article we will discuss how to create functions in Python that can accept variable length arguments in key value pair format.

Suppose we want to define a function that will print the provided students details. Details will be in key value pairs, where key represents the property name and value as property’s value.
It should print all the properties provided irrespective of their count i.e.

Should print 1 property i.e. name.

Should print 2 properties of student i.e. name & phone.

Should print 3 properties of student i.e name, phone & address.

Important things is that function should accepts variable length arguments in key value pair format. Let’s define a function like this,

Define function that accepts variable length arguments in key value pair using **kwargs

In Python if we want to accept multiple key value pair arguments in a single parameter then we need to add ** before the parameter name i.e.

Here **kwargs can accept multiple key value pair of arguments and will store them in dictionary i.e. kwargs will be of dictionary type.

Now let’s create the function using **kwargs i.e.

Now let’s pass variable number of key value pairs in this function,

Passing 3 key value pairs

Output

Passing 2 key value pairs

Output

Passing 1 key value pair

Output

Position of **kwargs , *args & Default Arguments

Positioning of arguments in function should be in this order,

  1. Formal Parameter
  2. *args Arguments
  3. Default Arguments
  4. **kwargs Arguments

Let’s create a function that accepts all the above mentioned types of arguments in order i.e.

Let’s call this function

Output:

Complete example is as follows,

Output

 

Click Here to Subscribe for more Articles / Tutorials like this.