Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

Question:

For instance, I’ve tried things like this, which doesn’t work:

mydict = {
    'funcList1': [foo(), bar(), goo()],
    'funcList2': [foo(), goo(), bar()]}

Is there some kind of structure with this kind of functionality?

I realize that I could obviously do this just as easily with a bunch of def statements:

def func1():
    foo()
    bar()
    goo()

But the number of statements I need is getting pretty unwieldy and tough to remember. It would be nice to wrap them nicely in a dictionary that I could examine the keys of now and again.

Asked By: Zack

||

Answers:

Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if foo and bar are functions, and dispatcher is a dictionary like so.

dispatcher = {'foo': foo, 'bar': bar}

Note that the values are foo and bar which are the function objects, and NOT foo() and bar().

To call foo, you can just do dispatcher['foo']()

EDIT: If you want to run multiple functions stored in a list, you can possibly do something like this.

dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}

def fire_all(func_list):
    for f in func_list:
        f()

fire_all(dispatcher['foobar'])
Answered By: Praveen Gollakota
# Lets say you have 10 programs or functions:
func_list = [program_001, program_002, program_003, program_004, program_005,
             program_006, program_007, program_008, program_009, program_010]

choose_program = int(input('Please Choose a program: ')) # input function number

func_list[choose_program - 1]()  
Answered By: Mohamed Hanafy

Case 1: Without Params.

The way that is employed to achieve this task is that the function name is kept as dictionary values, and while calling with keys, brackets ‘()’ are added.

# Python3 code to demonstrate the working of
# Functions as dictionary values
# Using Without params

# call Gfg fnc
def print_key1():
    return "This is Gfg's value"

# initializing dictionary
# check for function name as key
test_dict = {"Gfg": print_key1, "is": 5, "best": 9}

# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# calling function using brackets
res = test_dict['Gfg']()

# printing result
print("The required call result : " + str(res))

Case 2: With params

The task of calling with params is similar to the above case, the values are passed during the function call inside brackets as in usual function calls.

# Python3 code to demonstrate the working of
# Functions as dictionary values
# Using With params

# call Gfg fnc
def sum_key(a, b):
    return a + b

# initializing dictionary
# check for function name as key
test_dict = {"Gfg": sum_key, "is": 5, "best": 9}

# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# calling function using brackets
# params inside brackets
res = test_dict['Gfg'](10, 34)

# printing result
print("The required call result : " + str(res))

The original dictionary is: {‘Gfg’: <function sum_key at 0x7f538d017e18>, ‘is’: 5, ‘best’: 9}
The required call result: 44

SOURCE: geeksforgeeks

Answered By: Karam Qusai
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.