Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it’s values as argument values. Let’s discuss a method in which this can be performed.
Method : Using ** ( splat ) operator
This operator is used to unpack a dictionary, and while passing in a function this can possibly unpack a dictionary and achieve the required task of mapping the keys to arguments and it’s values to argument values.
# Python3 code to demonstrate working of # Passing dictionary as keyword arguments # Using ** ( splat ) operator # Helper function to demo this task def test_func(a = 4, b = 5): print("The value of a is : " + str(a)) print("The value of b is : " + str(b)) # initializing dictionary test_dict = {'a' : 1, 'b' : 2} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Testing with default values print("The default function call yields : ") test_func() print("\r") # Passing dictionary as keyword arguments # Using ** ( splat ) operator print("The function values with splat operator unpacking : ") test_func(**test_dict) |
The original dictionary is : {'a': 1, 'b': 2}
The default function call yields :
The value of a is : 4
The value of b is : 5
The function values with splat operator unpacking :
The value of a is : 1
The value of b is : 2
Recommended Posts:
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Pretty Print a dictionary with dictionary value
- Python | Convert string dictionary to dictionary
- Default arguments in Python
- Packing and Unpacking Arguments in Python
- Python | Set 6 (Command Line and Variable Arguments)
- Python | Passing Filenames to Extension in C
- finally keyword in Python
- Global keyword in Python
- Python | assert keyword
- Python | yield Keyword
- Python program to check if a given string is Keyword or not
- How to check if a string is a valid keyword in Python?
- Python | Get the first key in dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



