Re: Dictionary of Functions

Discussion in 'Python' started by MRAB, Nov 15, 2012.

  1. MRAB

    MRAB Guest

    On 2012-11-15 16:04, Kevin Gullikson wrote:
    > Hi all,
    >
    > I am trying to make a dictionary of functions, where each entry in the
    > dictionary is the same function with a few of the parameters set to
    > specific parameters. My actual use is pretty complicated, but I managed
    > to boil down the issue I am having to the following example:
    >
    > In [1]: def test_fcn(a, x):
    > ...: return a*x
    > ...:
    >
    > In [2]: fcn_dict = {}
    >
    > In [3]: for i in [1,2,3]:
    > ...: fcn_dict = lambda x: test_fcn(i, x)
    > ...:
    >
    > In [4]: fcn_dict
    > Out[4]:
    > {1: <function <lambda> at 0x102b42c08>,
    > 2: <function <lambda> at 0x102b42b18>,
    > 3: <function <lambda> at 0x102b42c80>}
    >
    > In [5]: fcn_dict[1](5)
    > Out[5]: 15
    >
    > In [6]: fcn_dict[2](5)
    > Out[6]: 15
    >
    > In [7]: fcn_dict[3](5)
    > Out[7]: 15
    >
    >
    > As you can see, all of the functions are returning the value that I want
    > for fcn_dict[3]. If I make separate functions for each case instead of a
    > dictionary it works, but I would really prefer to use dictionaries if
    > possible. Is there a way to make this work?
    >

    It's looking up 'i' at the time that the function is called, which is
    after the 'for' loop has finished and 'i' has been left as 3.

    What you need to do is capture the current value of 'i'. The usual way
    is with a default argument:

    for i in [1,2,3]:
    fcn_dict = lambda x, i=i: test_fcn(i, x)
    MRAB, Nov 15, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ilias Lazaridis
    Replies:
    6
    Views:
    434
    Ilias Lazaridis
    Feb 21, 2006
  2. james_027
    Replies:
    1
    Views:
    319
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  3. Navkirat Singh
    Replies:
    6
    Views:
    3,013
    Navkirat Singh
    Jul 29, 2010
  4. Chris Rebert
    Replies:
    0
    Views:
    519
    Chris Rebert
    Jul 29, 2010
  5. Fox

    dictionary within dictionary

    Fox, Mar 8, 2005, in forum: ASP General
    Replies:
    5
    Views:
    183
    Michael D. Kersey
    Mar 13, 2005
Loading...

Share This Page