Re: Dictionary of Functions

Discussion in 'Python' started by Chris Kaynor, Nov 15, 2012.

  1. Chris Kaynor

    Chris Kaynor Guest

    On Thu, Nov 15, 2012 at 8:04 AM, 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 this case, I would recommend using functools.partial instead of a lambda.
    It will solve this problem (although MRAB's solution will as well), is
    trivially faster (likely insignificant in any real application), and,
    IMO, clearer:

    for i in [1,2,3]:
    fcn_dict = functools.partial(test_fcn, i)

    Note that this only works if you are either only specifying the first
    arguments by position, or specifying arguments by keyword. There is no
    way to specify the second argument by position; you'd have to pass it
    as a keyword argument.
    Chris Kaynor, 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:
    427
    Ilias Lazaridis
    Feb 21, 2006
  2. james_027
    Replies:
    1
    Views:
    307
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  3. Navkirat Singh
    Replies:
    6
    Views:
    2,967
    Navkirat Singh
    Jul 29, 2010
  4. Chris Rebert
    Replies:
    0
    Views:
    504
    Chris Rebert
    Jul 29, 2010
  5. Fox

    dictionary within dictionary

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

Share This Page