Functions that accept variable length key value pair as arguments


Functions that take parameters in the form of variable-length key-value pairs can be defined in Python. This enables more dynamic and versatile functions that can handle a variety of inputs. When a function has to be able to handle arbitrary or optional parameters, this feature is frequently employed. Learn how to use the **kwargs and ** syntax to send a function a variable number of arguments in this technical article.

Syntax

The **kwargs syntax indicates that the function accepts an arbitrary number of keyword arguments, which are passed in as a dictionary.

def function_name(**kwargs):
   # code block

Algorithm

  • Define the function with the **kwargs parameter in the function signature.

  • Use the ** syntax to unpack the dictionary into named variables.

  • Use a for loop to iterate over the items in the kwargs dictionary.

  • Access the values using the key name.

Example

def print_values(**kwargs):
   for key, value in kwargs.items():
      print(key, value)

print_values(a=1, b=2, c=3)

Output

a 1                     
b 2
c 3

Example

def concatenate(**kwargs):
   result = ""
   for key, value in kwargs.items():
      result += str(value)
   return result
print(concatenate(a="Hello ", b="World ", c="!"))

Output

 Hello World !

Example

def calculate_average(**kwargs):
   values = [value for value in kwargs.values() if isinstance(value, int) or isinstance(value, float)]
   return sum(values) / len(values)

print(calculate_average(a=1, b=2.5, c="hello"))

Output

1.75

Explanation

The print values function uses a for loop to display any number of key-value pairs that are provided to it while iterating over the dictionary's items() method. Prior to concatenating all of the items passed in as key-value pairs, the concatenate method returns each value to a string. While computing the average of all the data provided as key-value pairs, the resulting average function solely considers numeric values. Also note that you need to see the isinstance() function to determine whether a value is a number.

What if we want to create a function that not only accepts a person's name, age, and location but also accepts additional key-value pair arguments as optional arguments −

def person_info(name, age, location, **kwargs):
   print("Name:", name)
   print("Age:", age)
   print("Location:", location)
    
   for key, value in kwargs.items():
      print(key.capitalize() + ":", value)

person_info("Alice", 25, "New York", occupation="Engineer", hobbies=["Reading", "Hiking"])

Output

Name: Alice
Age: 25
Location: New York
Occupation: Engineer
Hobbies: ['Reading', 'Hiking']

Name, age, and location are the three mandatory parameters in this example. Moreover, any number of additional optional key-value pairs may be given. We run over the items() function of the kwargs dictionary and use a for loop to prepare the key-value pairs before printing them out.

Applications

  • Creating APIs that can change − Clients can pass in additional information that the capability can deal with in various ways by involving variable-length key-val pair contentions in the capability's Programming interface.

  • Managing non-essential arguments − Optional arguments can be created using variable-length key-value pair arguments, and function definitions can include both mandatory and optional arguments. As such, calling the capability with just the boundaries that are vital or with quite a few extra boundaries is conceivable.

  • Parsing arguments from the command line − A program or content's order line boundaries can be characterized utilizing Python's underlying argparse module. The module acknowledges key-esteem pair boundaries of different length, permitting the client to give additional contentions.

Conclusion

Because they provide methods for developing functions that can handle a variety of inputs and are simple to use, Python's strong variable-length key-value pair parameters make it possible to develop functions that are more adaptable and dynamic. By utilizing this feature, you can enhance the user experience as well as the robustness and adaptability of your code.

Updated on: 22-Aug-2023

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements