Python – Store Function as dictionary value
Last Updated :
16 Feb, 2023
Given a dictionary, assign its keys as function calls.
Case 1 : Without Params.
The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets ‘()’ are added.
Python3
def print_key1():
return "This is Gfg's value"
test_dict = { "Gfg" : print_key1, "is" : 5 , "best" : 9 }
print ( "The original dictionary is : " + str (test_dict))
res = test_dict[ 'Gfg' ]()
print ( "The required call result : " + str (res))
|
Output
The original dictionary is : {'Gfg': <function print_key1 at 0x7f1c0445be18>, 'is': 5, 'best': 9}
The required call result : This is Gfg's value
Time Complexity: O(n)
Auxiliary Space: O(1)
Case 2 : With params
The task of calling with params is similar to above case, the values are passed during function call inside brackets as in usual function calls.
Python3
def sum_key(a, b):
return a + b
test_dict = { "Gfg" : sum_key, "is" : 5 , "best" : 9 }
print ( "The original dictionary is : " + str (test_dict))
res = test_dict[ 'Gfg' ]( 10 , 34 )
print ( "The required call result : " + str (res))
|
Output
The original dictionary is : {'Gfg': <function sum_key at 0x7f538d017e18>, 'is': 5, 'best': 9}
The required call result : 44
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...