Open In App

Functions that accept variable length key value pair as arguments

Last Updated : 15 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 in their function.

Syntax:

def functionName(**anything):
    statement(s)

Note: adding ‘**‘ to any term makes it a kwargs parameter. It accepts keywords as arguments. 

Example #1: 

Python3




# using kwargs
# in functions
 
 
def printKwargs(**kwargs):
    print(kwargs)
 
 
# driver code
if __name__ == "__main__":
    printKwargs(Argument_1='gfg', Argument_2='GFG')


Output:

{'Argument_1': 'gfg', 'Argument_2': 'GFG'}

Example #2:

Python3




# using kwargs
# in functions
 
 
def printValues(**kwargs):
    for key, value in kwargs.items():
        print("The value of {} is {}".format(key, value))
 
 
# driver code
if __name__ == '__main__':
    printValues(abbreviation="GFG", full_name="geeksforgeeks")


Output:

The value of abbreviation is GFG
The value of full_name is geeksforgeeks

Example #3:

Python3




# using kwargs
# in functions
# to concatenate
 
 
def concatenate(**arguments):
    # initialising empty string
    final_str = ""
     
    # Iterating over the Python kwargs
    # dictionary
    for elements in arguments.values():
        final_str += elements
    return final_str
 
 
# driver code
if __name__ == '__main__':
    print(concatenate(a="g", b="F", c="g"))


Output:

gFg

Example #4:

Python3




# using kwargs
# to multiply
 
 
def multiply(**kwargs):
   
    # initialising answer
    answer = 1
     
    # Iterating over the Python kwargs
    # dictionary
    for elements in kwargs.values():
        answer *= elements
    return answer
 
 
# driver code
if __name__ == '__main__':
    print(multiply(a=1, b=2, c=3, d=4, e=5))


Output:

120


Previous Article
Next Article

Similar Reads

Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
2 min read
Executing functions with multiple arguments at a terminal in Python
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python sys module allows access to command-line argument
4 min read
Python - Filter key's value from other key
Sometimes, while working with Python dictionary, we can have a problem in which we need to extract a value from dictionary list of the key on basis of some other key equality. This kind of problem is common in domains that include data, for e.g web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [{'g
7 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Add a key:value pair to dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. While using Dictionary, sometimes, we need to add or modify the key/value inside the dictionary. Let's see how to add a key:value pair to dict
2 min read
Python | Convert byteString key:value pair of dictionary to String
Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string. Examples: Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' } Output: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'} Input: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' } Output: {'Key1':'Geeks', 'Key
4 min read
Python | Convert key-value pair comma separated string into dictionary
Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task. Method #1: Using dictionary comprehension
5 min read
Python program to Count the Number of occurrences of a key-value pair in a text file
Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with Python Program to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular expressions (re module)Text file: Naive Approach to
3 min read
Python: Key Value pair using argparse
The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. It also automatically generates help and usage messages and issues errors when users give the program invalid arguments. Steps For Using Argparse Module: Creating a Parser: Importing argparse
2 min read
Python - Convert each list element to key-value pair
Given list of elements, convert each element to a key-value pair dictionary, dividing digits equally. Input : test_list = [2323, 82, 129388, 234, 95] Output : {23: 23, 8: 2, 129: 388, 2: 34, 9: 5} Explanation : Digits distributed equally to keys and values. Input : test_list = [2323, 82, 129388] Output : {23: 23, 8: 2, 129: 388} Explanation : Digit
2 min read
Practice Tags :
three90RightbarBannerImg