5 Examples to Understand Keyword Arguments in Python

The functional programming approach gives us the ease of DRY (do not repeat yourself) programming. It is declarative programming where programs are created using sequential functions rather than writing all the statements. We can reuse them as per our needs. The function we create takes some input and returns some output or performs some operations. Now, the input it takes maybe as the arguments or directs from I/O. Today in this article, we will discuss one such method of feeding input to function, i.e., Keyword Argument in python. So, let’s go.

What is Keyword Argument in Python?

While defining a function, we set some parameters within it. We accept data in these parameters from function calls. Now, python provides the feature of accepting the parameters in several ways, e.g., positional arguments or keyword arguments. Keyword Arguments are used when we used to assign values to the function parameter as the key-value pair. In simple words, we use keyword arguments to assign values to a particular variable.

Why do we need Keyword Arguments?

While passing the arguments to functions, sometimes we know the number of parameters; contrary, it also happens that we don’t know the number of arguments. Both the scenarios are known as a fixed number of arguments or the arbitrary number of arguments respectively. Keyword arguments give us the ability to handle the arbitrary number of arguments as the key-value pair. The keyword arguments start with the “**” symbol followed by a variable name. Let’s see some of the examples to understand them better.

Example 1: Passing arguments to Keyword parameter

# Example on arguments and keyword arguments

def func(a,*args,**kwargs):
  print(a)

  # Using arbitrary number of arguments as positional argument
  for arg in args:
    print(arg)
    
  # Using arbitrary number of arguments as keyword argument
  for key,value in kwargs.items():
    print('{} = {}'.format(key,value))

func('Hii','I','am',name ='Python Pool', From ='Latracal Solution')

Output:

Hii
I
am
name = Python Pool
From = Latracal Solution

Explanation

So, in the above example, we created a function and then used three types of parameters to accept arguments. The first is a known parameter, the other is to accept a number of arbitrary arguments, and the last is to accept the number of keyword arguments. Then, we use for loop to access elements in the args and kwargs variables.

Example 2: Passing keywords as Arguments

def func(arg1,arg2,arg3,arg4):
  print(arg1)
  print(arg2)
  print(arg3)
  print(arg4)

a = ("This","is",'positional','argument')

b = {"arg1":'This','arg2':'is','arg3':'keyword','arg4':'argument'}

# Passing positional argument to the function
func(*a)
print("---------")

# Passing keyword argument to the function
func(**b)

Output:

This
is
positional
argument
---------
This
is
keyword
argument

Explanation

We created a tuple and a dictionary to pass them as the argument in the above example. This demonstrates that it is also easy to pass multiple values to function as arguments. We need to create variables and use “*” and “**” to specify the types of arguments.

Example 3: Keyword Arguments as Python Dictionary

So, have you ever thought about how these keyword arguments work? Or how the keywords map to their values when passing as the arguments. All this happens because the arguments we pass are passed in the form of a dictionary. It helps smooth mapping to every key for corresponding values without losing its entity. Let’s see the example.

def kwargs_to_dict(**kwargs):
  print(type(kwargs))
  print(kwargs)
kwargs_to_dict(name ='Python Pool', From ='Latracal Solution')

Output:

<class 'dict'>
{'name': 'Python Pool', 'From': 'Latracal Solution'}

Explanation

So, in the above example, we have seen what the kwargs variable’s data type is and then printed it to get its content.

Example 4: Keyword Arguments Using Lambda Function

Besides all the features of the lambda function, it is also compatible with multiple parameters while working. Now, these parameters are either in the form of arguments or keyword arguments. Let’s see the example and learn how we can handle that.

x = (lambda **kwargs : sum(kwargs.values())/len(kwargs))
x(one = 1, two = 2, three = 3)

Output:

2.0

Explanation

So, in the above example, we can see that we created a lambda function x. And we used three keyword arguments for calling the function and then tried to find its average. To access each value from the dictionary, we used the values() function and then calculated its average.

Example 5: Keyword Arguments Python Argparse

#importing argparse module
import argparse

class KeyValue(argparse.Action):
	def __call__( self , parser, namespace,
				values, option_string = None):
		setattr(namespace, self.dest, dict())
		
		for value in values:
			# split it into key and value
			key, value = value.split('=')
			# Adding it as dictionary
			getattr(namespace, self.dest)[key] = value

# Initializing parser object
parser = argparse.ArgumentParser()

# adding an arguments
parser.add_argument('--kwargs',nargs='*',action = KeyValue)

#parsing arguments
args = parser.parse_args()

# show the dictionary
print(args.kwargs)

Explanation

In the above example, we first created a class that inherits from the agrparse class where we write a similar kind of code as explained in example 2 to add elements in the dictionary. Then we initialized an object for argparse.Argparser to hold the values of arguments from CLI. Then we added that element in the parser variable, parsed the arguments and had it in the args variable. And then printed the values of the dictionary.

FAQs on Keyword Argument in Python

Q1) What is the difference between arguments and keyword arguments in python?

Arguments or Positional arguments must be passed incorrectly, while keyword argument must be passed with the keyword that corresponds to some value.

Q2) Can keyword arguments be in any order?

Yes, it is passed as the dictionary, so the arguments are available as key-value pairs. Hence, Its order does not matter.

Q3) Keyword vs. positional arguments python?

Keyword arguments are passed as arguments for the convenience of receiving the values corresponding to some key. In comparison, positional arguments are passed based on their position.

Conclusion

So, today in this article, we learned keyword arguments in python and how we can use them to pass the arguments to a function and accept them as the argument. I hope this article has helped you. Thank You.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments