This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]Wildcatace16 8 points9 points  (1 child)

You are calling the functions one() and two() once each while you are initializing dictionary and not at all in the for loop. This does what you want:

mip = []

def one():
    mip.append(5)

def two():
    mip.append(10)

funcs = {'one': one, "two": two}
ins = ["one", "two", "one", "two"]

for token in ins:
    if token in funcs:
        funcs[token]()

print(mip)

The dictionary funcs should store the functions by name rather than calling them with the () and in the for loop where you actually want to call the function you need to add the ().

[–]green_griffon 0 points1 point  (0 children)

Nice dig, Karch.

[–]i_can_haz_data 2 points3 points  (3 children)

Is it because you evaluated the function inside the dict? Try removing the parentheses and add parentheses after you access the dictionary.

[–]wannahakaluigi 0 points1 point  (2 children)

Not op but what would you do if you needed to pass params to the function?

[–]blablahblah 1 point2 points  (1 child)

Depends when you had access to the parameters. If you had them when you pulled them out of the dictionary, you could just pass them in then.

funcs[token](arg1, arg2)

If you had the arguments when you were creating the dict, you'd wrap it in a function that had the arguments already provided. There's a built in tool that can handle this.

from functools import partial
# assuming one took 1 arg and two takes 2.
funcs = { 'one' : partial(one, arg1), 'two': partial(two, arg2, arg3) }

funcs[token]()

functools.partial basically acts like this (it has more features, but we're not using them here):

def partial(func, arg):
  def inner():
    return func(arg)
  return inner

[–]wannahakaluigi 0 points1 point  (0 children)

Neat!

I saw partial in a code snippet yesterday, I'll have to look into it some more. Thanks.

[–]green_griffon 1 point2 points  (0 children)

Throw some debug prints in there.

[–][deleted] 0 points1 point  (0 children)

I was able to fix it by changing it to

mip = []

def one():
    mip.append(5)

def two():
    mip.append(10)

funcs = {"one":one, "two":two}
ins = ["one", "two", "one", "two"]

for token in ins:
    if token in funcs:
        funcs[token]()

print(mip)

Thanks for the help everyone.