mapping functions and lambda

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Suresh Jeevanandam

    #1

    mapping functions and lambda

    Given a string
    s = 'a=1,b=2'

    I want to create a dictionary {'a': '1', 'b': '2'}

    I did,

    dict(map(lambda k: k.split('='), s.split(',')))

    Is it possible to get rid of the lambda here, without having to define
    another function just for this.

    Is this the easiest/straight-forward way to do this?

    regards,
    Suresh
  • Suresh Jeevanandam

    #2
    Re: mapping functions and lambda

    I got it:
    dict([k.split('=') for k in s.split(',')])

    regards,
    Suresh
    Suresh Jeevanandam wrote:[color=blue]
    > Given a string
    > s = 'a=1,b=2'
    >
    > I want to create a dictionary {'a': '1', 'b': '2'}
    >
    > I did,
    >
    > dict(map(lambda k: k.split('='), s.split(',')))
    >
    > Is it possible to get rid of the lambda here, without having to define
    > another function just for this.
    >
    > Is this the easiest/straight-forward way to do this?
    >
    > regards,
    > Suresh[/color]

    Comment

    • Steve Holden

      #3
      Re: mapping functions and lambda

      Suresh Jeevanandam wrote:[color=blue]
      > I got it:
      > dict([k.split('=') for k in s.split(',')])
      >
      > Suresh Jeevanandam wrote:
      >[color=green]
      >>Given a string
      >>s = 'a=1,b=2'
      >>
      >>I want to create a dictionary {'a': '1', 'b': '2'}
      >>
      >>I did,
      >>
      >>dict(map(lamb da k: k.split('='), s.split(',')))
      >>
      >>Is it possible to get rid of the lambda here, without having to define
      >>another function just for this.
      >>
      >>Is this the easiest/straight-forward way to do this?
      >>[/color][/color]

      In Python 2.4 you don't even need to construct the list, you can just
      use a generator expression instead:

      dict(k.split('= ') for k in s.split(','))

      regards
      Steve
      --
      Steve Holden +44 150 684 7255 +1 800 494 3119
      Holden Web LLC www.holdenweb.com
      PyCon TX 2006 www.python.org/pycon/

      Comment

      Working...