RJK
RJK

Reputation: 242

Dictionary mapping multiple functions to key - Python

I understand we can use dictionary mapping with functions like this:

def call_functions(input)
    def function1():
        print "called function 1"

    def function2():
        print "called function 2"

    def function3():
        print "called function 3"

    tokenDict = {"cat":function1, 
                 "dog":function2, 
                 "bear":function3}

    return tokenDict[input]()

But what if we want to set two functions as a value in the dictionary? Like:

tokenDict = {"cat":function1, function2
             "dog":function2
             ....

I tried using a list like "cat":[function1, function2] but is there an easier way to do it?

When I call it, I want it to execute function1 and then function2

Upvotes: 1

Views: 1455

Answers (2)

Green Cloak Guy
Green Cloak Guy

Reputation: 24711

What do you mean "assign two functions to a key"? For that matter, what do you mean with assigning two anythings to a dictionary key? You need to bundle them together somehow, because the entire point of a dictionary is that each key corresponds to exactly one value (if that value is a bundle, so be it). The other answer covers that.

If you want both of those functions to be executed, and you're not going to be changing this approach much in the immediate future, you could also use a wrapper function that simply calls them in sequence:

def function4:
    function1()
    function2()

Upvotes: 1

jpp
jpp

Reputation: 164843

As per Tyler's comment, use lists throughout for consistency. Then use a list comprehension to output the result of applying each function in your list. Here's a working example:

def call_functions(i, val=3):

    def function1(x):
        return x*1

    def function2(x):
        return x*2

    def function3(x):
        return x*3

    tokenDict = {"cat": [function1, function2],
                 "dog": [function2], 
                 "bear": [function3]}

    return [f(val) for f in tokenDict[i]]

call_functions('cat')   # [3, 6]
call_functions('dog')   # [6]
call_functions('bear')  # [9]

Side note: you should not shadow the built-in input.

Upvotes: 4

Related Questions