1

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

3
  • 2
    Treat your value as a list always. That way you have a list of 1 or more operations and you can handle the operations in the same way no matter what number of operations you have. Commented Jul 23, 2018 at 18:06
  • Wrap the two functions in another function: "cat": lambda: function1(), function2(). Commented Jul 23, 2018 at 18:12
  • @Tyler. Alternatively, you can write a single function that returns a list of values. Commented Jul 23, 2018 at 18:37

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.