Python – Store Function as dictionary value

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
# Python3 code to demonstrate working of# Functions as dictionary values# Using Without params# call Gfg fncdef print_key1(): return "This is Gfg's value"# initializing dictionary# check for function name as keytest_dict = {"Gfg": print_key1, "is" : 5, "best" : 9}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# calling function using bracketsres = test_dict['Gfg']()# printing resultprint("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
# Python3 code to demonstrate working of# Functions as dictionary values# Using With params# call Gfg fncdef sum_key(a, b): return a + b# initializing dictionary# check for function name as keytest_dict = {"Gfg": sum_key, "is" : 5, "best" : 9}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# calling function using brackets# params inside bracketsres = test_dict['Gfg'](10, 34)# printing resultprint("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



