Functions that Accept Variable Length Key Value Pair as Arguments
To pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.
kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments (arguments passed with a specific name (key) along with their value) in their function.
Here's an example:
def func(**kwargs):
for key, val in kwargs.items():
print(key, ": ", val)
func(name="GFG", country="India")
Output
name : GFG country : India
Syntax:
def functionName(**kwargs):
# code
kwargs: it's the variable name using which we can access the arguments keys and values.
Note: adding '**' to any term makes it a kwargs parameter. It accepts keywords as arguments.
Let's discuss some use cases of **kwargs with examples to get a better understanding.
Passing and Printing Key-Value Pairs
In this example, we define a function that accepts keyword arguments and prints them as a dictionary.
def func(**kwargs):
print(kwargs)
func(k1 = "Geeks", k2 = "For", k3 = "Geeks")
Output
{'k1': 'Geeks', 'k2': 'For', 'k3': 'Geeks'}
Iterating Through Keyword Arguments
We can loop through kwargs using kwargs.items() to access both the keys and values.
def func(**kwargs):
for key, val in kwargs.items():
print("The value of ", key," is", val)
func(short_form = "GFG", full_name="geeksforgeeks")
Output
The value of short_form is GFG The value of full_name is geeksforgeeks
Concatenating String Arguments
This example shows how **kwargs can be used to concatenate multiple string values passed as keyword arguments.
def func(**kwargs):
# initialising empty string
s = ""
for ele in kwargs.values():
s += ele
return s
print(func(a="g", b="F", c="g"))
Output
gFg
Multiplying Numeric Values
We can easily perform arithmetic operations over the items of argumets.
def func(**kwargs):
ans = 1
for ele in kwargs.values():
ans *= ele
return ans
print(func(a=1, b=2, c=3, d=4, e=5))
Output
120
Merging Two Dictionaries
We can create a function that accepts two dictionaries as keyword arguments and merges them into one.
def func(**kwargs):
res = {}
for key, val in kwargs.items():
res[key] = val
return res
print(func(first={"a": 1, "b": 2}, second={"c": 3, "d": 4}))
Output
{'first': {'a': 1, 'b': 2}, 'second': {'c': 3, 'd': 4}}
Formatting a String with Dynamic Values
Using **kwargs, we can accept multiple key-value pairs and dynamically format them into a structured string. This is particularly useful when dealing with flexible data inputs, such as logging messages, creating query strings, or displaying structured information.
def func(**kwargs):
return " ".join([f"{key}={val}" for key, val in kwargs.items()])
print(func(name="GfG",country="India"))
Output
name=GfG country=India
Explanation:
- accessing key-value data using for key, value in kwargs.items().
- " ".join(formatted_pairs) combines the formatted key-value pairs into a single string, separated by spaces.