problem of converting a list to dict

Discussion in 'Python' started by Louis.Soninhu@gmail.com, Jan 9, 2008.

  1. Guest

    Hi pals

    I have a list like this

    mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

    I'd like to remove the first and the last item as they are irrevalent,
    and convert it to the dict:
    {'tom':'boss','mike':'manager','paul':'employee'}

    I tried this but it didn't work:

    mydict={}
    for i in mylist[1:-1]:
    a=i.split('=') # this will disect each item of mylist into a 2-item
    list
    mydict[a[0]]=a[1]

    and I got this:
    File "srch", line 19, in <module>
    grab("a/tags1")
    File "srch", line 15, in grab
    mydict[mylist[0]]=mylist[1]
    IndexError: list index out of range

    Anyone could shed me a light on this?

    thanks
     
    , Jan 9, 2008
    #1
    1. Advertising

  2. wrote:

    > I have a list like this
    >
    > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
    >
    > I'd like to remove the first and the last item as they are irrevalent,
    > and convert it to the dict:
    > {'tom':'boss','mike':'manager','paul':'employee'}
    >
    > I tried this but it didn't work:
    >
    > mydict={}
    > for i in mylist[1:-1]:
    > a=i.split('=')
    > mydict[a[0]]=a[1]
    >
    > and I got this:
    > File "srch", line 19, in <module>
    > grab("a/tags1")
    > File "srch", line 15, in grab
    > mydict[mylist[0]]=mylist[1]
    > IndexError: list index out of range
    >
    > Anyone could shed me a light on this?


    works for me, with the mylist example you provided.

    to see what's going on on your machine, try printing "a" after the
    split, but before you use it to populate the dictionary.

    </F>
     
    Fredrik Lundh, Jan 9, 2008
    #2
    1. Advertising

  3. On Wed, 09 Jan 2008 10:56:36 -0800, Louis.Soninhu wrote:

    > Hi pals
    >
    > I have a list like this
    >
    > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
    >
    > I'd like to remove the first and the last item as they are irrevalent,
    > and convert it to the dict:
    > {'tom':'boss','mike':'manager','paul':'employee'}
    >
    > I tried this but it didn't work:
    >
    > mydict={}
    > for i in mylist[1:-1]:
    > a=i.split('=') # this will disect each item of mylist into a 2-item
    > list
    > mydict[a[0]]=a[1]
    >
    > and I got this:
    > File "srch", line 19, in <module>
    > grab("a/tags1")
    > File "srch", line 15, in grab
    > mydict[mylist[0]]=mylist[1]
    > IndexError: list index out of range
    >
    > Anyone could shed me a light on this?


    The real list you used had at least one string without a '=' in it. The
    list given above doesn't raise that exception:

    In [102]: mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

    In [103]: mydict={}

    In [104]: for i in mylist[1:-1]:
    .....: a=i.split('=')
    .....: mydict[a[0]]=a[1]
    .....:

    In [105]: mydict
    Out[105]: {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

    Ciao,
    Marc 'BlackJack' Rintsch
     
    Marc 'BlackJack' Rintsch, Jan 9, 2008
    #3
  4. Guest

    that's very strange...

    the list I give here is almost same as the real list, except for the
    length.

    Thanks Marc, I'll go check what's wrong elsewhere
     
    , Jan 9, 2008
    #4
  5. Guest

    On Jan 9, 3:05 pm, Fredrik Lundh <> wrote:
    > wrote:
    > > I have a list like this

    >
    > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

    >
    > > I'd like to remove the first and the last item as they are irrevalent,
    > > and convert it to the dict:
    > > {'tom':'boss','mike':'manager','paul':'employee'}

    >
    > > I tried this but it didn't work:

    >
    > > mydict={}
    > > for i in mylist[1:-1]:
    > >    a=i.split('=')
    > >    mydict[a[0]]=a[1]

    >
    > > and I got this:
    > >   File "srch", line 19, in <module>
    > >     grab("a/tags1")
    > >   File "srch", line 15, in grab
    > >     mydict[mylist[0]]=mylist[1]
    > > IndexError: list index out of range

    >
    > > Anyone could shed me a light on this?

    >
    > works for me, with the mylist example you provided.
    >
    > to see what's going on on your machine, try printing "a" after the
    > split, but before you use it to populate the dictionary.
    >
    > </F>- Hide quoted text -
    >
    > - Show quoted text -


    'print a' works
     
    , Jan 9, 2008
    #5
  6. wrote:

    >> to see what's going on on your machine, try printing "a" after the
    >> split, but before you use it to populate the dictionary.

    >
    > 'print a' works


    so what does it tell you?

    </F>
     
    Fredrik Lundh, Jan 9, 2008
    #6
  7. John Machin Guest

    On Jan 10, 5:56 am, wrote:
    > Hi pals
    >
    > I have a list like this
    >
    > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
    >
    > I'd like to remove the first and the last item as they are irrevalent,
    > and convert it to the dict:
    > {'tom':'boss','mike':'manager','paul':'employee'}
    >
    > I tried this but it didn't work:
    >
    > mydict={}
    > for i in mylist[1:-1]:
    > a=i.split('=') # this will disect each item of mylist into a 2-item


    No it doesn't; it dissects i into a 2-item list if i is a string
    containing exactly one '='.

    DON'T rely on "knowing" that the first and last entries are the only
    irrelevant ones. Do some checking. Conditions to check for:
    (1) len(a) == 2
    (2) a[0] is empty or not what you expect (a person's name)
    (3) a[1] is empty or not what you expect (a job title)
    (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
    boss')
    (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]
     
    John Machin, Jan 9, 2008
    #7
  8. > -----Original Message-----
    > From: python-list-bounces+jr9445= [mailto:python-
    > list-bounces+jr9445=] On Behalf Of Fredrik Lundh
    > Sent: Wednesday, January 09, 2008 2:39 PM
    > To:
    > Subject: Re: problem of converting a list to dict
    >
    > wrote:
    >
    > >> to see what's going on on your machine, try printing "a" after the
    > >> split, but before you use it to populate the dictionary.

    > >
    > > 'print a' works

    >
    > so what does it tell you?
    >


    A bigger hint:
    a=i.split('=')
    print "'%s' splits into " % (i), a
    assert len(a) == 2
    mydict[a[0]]=a[1]
     
    Reedick, Andrew, Jan 9, 2008
    #8
  9. Guest

    oops, it seems there are other 'meaningless' item, which actually
    caused the problem

    Thanks for helps
     
    , Jan 9, 2008
    #9
  10. John Machin Guest

    On Jan 10, 6:52 am, "Reedick, Andrew" <> wrote:
    > > -----Original Message-----
    > > From: python-list-bounces+jr9445= [mailto:python-
    > > list-bounces+jr9445=] On Behalf Of Fredrik Lundh
    > > Sent: Wednesday, January 09, 2008 2:39 PM
    > > To:
    > > Subject: Re: problem of converting a list to dict

    >
    > > wrote:

    >
    > > >> to see what's going on on your machine, try printing "a" after the
    > > >> split, but before you use it to populate the dictionary.

    >
    > > > 'print a' works

    >
    > > so what does it tell you?

    >
    > A bigger hint:
    > a=i.split('=')
    > print "'%s' splits into " % (i), a


    consider:
    (1) using %r instead of '%s'
    (2) omitting the redundant space after 'into'
    (3) losing the redundant () around i


    > assert len(a) == 2
    > mydict[a[0]]=a[1]
     
    John Machin, Jan 9, 2008
    #10
  11. Tim Chase Guest

    > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
    >
    > I'd like to remove the first and the last item as they are irrevalent,
    > and convert it to the dict:
    > {'tom':'boss','mike':'manager','paul':'employee'}
    >
    > I tried this but it didn't work:
    >
    > mydict={}
    > for i in mylist[1:-1]:
    > a=i.split('=') # this will disect each item of mylist into a 2-item
    > list
    > mydict[a[0]]=a[1]
    >
    > and I got this:
    > File "srch", line 19, in <module>
    > grab("a/tags1")
    > File "srch", line 15, in grab
    > mydict[mylist[0]]=mylist[1]
    > IndexError: list index out of range


    This can be rewritten a little more safely like

    mydict = dict(pair.split('=',1)
    for pair in mylist
    if '=' in pair)

    Some of John Machin's caveats still apply:
    (2) a[0] is empty or not what you expect (a person's name)
    (3) a[1] is empty or not what you expect (a job title)
    (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
    boss')
    (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]

    to which I'd add

    (5) what happens if you have more than one equals-sign in your
    item? ("bob=robert=manager" or "bob=manager=big-cheese")


    #2 and #3 can be ameliorated a bit by

    import string
    mydict = dict(
    map(string.strip,pair.split('=',1))
    for pair in mylist
    if '=' in pair)

    which at least whacks whitespace off either end of your keys and
    values. #4 and #5 require a clearer definition of the problem.

    -tkc
     
    Tim Chase, Jan 9, 2008
    #11
  12. John Machin Guest

    On Jan 10, 7:12 am, Tim Chase <> wrote:
    > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

    >
    > > I'd like to remove the first and the last item as they are irrevalent,
    > > and convert it to the dict:
    > > {'tom':'boss','mike':'manager','paul':'employee'}

    >
    > > I tried this but it didn't work:

    >
    > > mydict={}
    > > for i in mylist[1:-1]:
    > > a=i.split('=') # this will disect each item of mylist into a 2-item
    > > list
    > > mydict[a[0]]=a[1]

    >
    > > and I got this:
    > > File "srch", line 19, in <module>
    > > grab("a/tags1")
    > > File "srch", line 15, in grab
    > > mydict[mylist[0]]=mylist[1]
    > > IndexError: list index out of range

    >
    > This can be rewritten a little more safely like
    >
    > mydict = dict(pair.split('=',1)
    > for pair in mylist
    > if '=' in pair)
    >
    > Some of John Machin's caveats still apply:
    > (2) a[0] is empty or not what you expect (a person's name)
    > (3) a[1] is empty or not what you expect (a job title)
    > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
    > boss')
    > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]
    >
    > to which I'd add
    >
    > (5) what happens if you have more than one equals-sign in your
    > item? ("bob=robert=manager" or "bob=manager=big-cheese")
    >


    or "bob==manager"

    ummm ... isn't more than one equals-sign covered by check #1: len(a)
    == 2
    ?
     
    John Machin, Jan 9, 2008
    #12
  13. bsneddon Guest

    On Jan 9, 3:12 pm, Tim Chase <> wrote:
    > > mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

    >
    > > I'd like to remove the first and the last item as they are irrevalent,
    > > and convert it to the dict:
    > > {'tom':'boss','mike':'manager','paul':'employee'}

    >
    > > I tried this but it didn't work:

    >
    > > mydict={}
    > > for i in mylist[1:-1]:
    > > a=i.split('=') # this will disect each item of mylist into a 2-item
    > > list
    > > mydict[a[0]]=a[1]

    >
    > > and I got this:
    > > File "srch", line 19, in <module>
    > > grab("a/tags1")
    > > File "srch", line 15, in grab
    > > mydict[mylist[0]]=mylist[1]
    > > IndexError: list index out of range

    >
    > This can be rewritten a little more safely like
    >
    > mydict = dict(pair.split('=',1)
    > for pair in mylist
    > if '=' in pair)
    >
    > Some of John Machin's caveats still apply:
    > (2) a[0] is empty or not what you expect (a person's name)
    > (3) a[1] is empty or not what you expect (a job title)
    > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
    > boss')
    > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]
    >
    > to which I'd add
    >
    > (5) what happens if you have more than one equals-sign in your
    > item? ("bob=robert=manager" or "bob=manager=big-cheese")
    >
    > #2 and #3 can be ameliorated a bit by
    >
    > import string
    > mydict = dict(
    > map(string.strip,pair.split('=',1))
    > for pair in mylist
    > if '=' in pair)
    >
    > which at least whacks whitespace off either end of your keys and
    > values. #4 and #5 require a clearer definition of the problem.
    >
    > -tkc


    This seemed to work for me if you are using 2.4 or greater and
    like list comprehension.
    >>> dict([ tuple(a.split("=")) for a in mylist[1:-1]])

    {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

    should be faster than looping
     
    bsneddon, Jan 9, 2008
    #13
  14. > -----Original Message-----
    > From: python-list-bounces+jr9445= [mailto:python-
    > list-bounces+jr9445=] On Behalf Of John Machin
    > Sent: Wednesday, January 09, 2008 3:02 PM
    > To:
    > Subject: Re: problem of converting a list to dict
    >
    > On Jan 10, 6:52 am, "Reedick, Andrew" <> wrote:
    > >
    > > A bigger hint:
    > > a=i.split('=')
    > > print "'%s' splits into " % (i), a

    >
    > consider:
    > (1) using %r instead of '%s'


    Eh, personal preference depending on how sure you are of the
    data's type.

    > (2) omitting the redundant space after 'into'


    Some of us coming in from other languages and still aren't used
    to the comma adding an unwanted space after everything. I've been
    tempted to root around in Python's source code to fix the problem.

    > (3) losing the redundant () around i


    For me, the () is there for readability. Python's sprintf
    syntax is odd to begin with, and something like
    print "'%s' splits into " % i, a, b, c
    means either
    1) you really do want to append b and c after the
    sprintf, or
    print "'%s' splits into " % (a), b, c
    2) that the formatting string is missing a few things
    print "'%s' splits into " % (a, b, c) ## Ooops!
    forgot to change it to "%s %5.2d %6.3f"


    *****

    The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622
     
    Reedick, Andrew, Jan 9, 2008
    #14
  15. Mike Meyer Guest

    On Wed, 9 Jan 2008 14:34:26 -0600 "Reedick, Andrew" <> wrote:

    > > -----Original Message-----
    > > From: python-list-bounces+jr9445= [mailto:python-
    > > list-bounces+jr9445=] On Behalf Of John Machin
    > > Sent: Wednesday, January 09, 2008 3:02 PM
    > > To:
    > > Subject: Re: problem of converting a list to dict
    > >
    > > On Jan 10, 6:52 am, "Reedick, Andrew" <> wrote:
    > > >
    > > > A bigger hint:
    > > > a=i.split('=')
    > > > print "'%s' splits into " % (i), a

    > >
    > > consider:
    > > (1) using %r instead of '%s'

    >
    > Eh, personal preference depending on how sure you are of the
    > data's type.
    >
    > > (2) omitting the redundant space after 'into'

    >
    > Some of us coming in from other languages and still aren't used
    > to the comma adding an unwanted space after everything. I've been
    > tempted to root around in Python's source code to fix the problem.
    >
    > > (3) losing the redundant () around i

    >
    > For me, the () is there for readability. Python's sprintf
    > syntax is odd to begin with, and something like
    > print "'%s' splits into " % i, a, b, c
    > means either
    > 1) you really do want to append b and c after the
    > sprintf, or
    > print "'%s' splits into " % (a), b, c
    > 2) that the formatting string is missing a few things
    > print "'%s' splits into " % (a, b, c) ## Ooops!
    > forgot to change it to "%s %5.2d %6.3f"


    In that case, I'd suggest making the right operand a tuple:

    print "'%s' splits into" % (i,), a, b, c

    which some will argue is good style in any case. Or if you just want
    to aide readers not used to python, use the redundant parens to
    enforce the default parsing:

    print ("'%s' splits into" % i), a, b, c

    <mike
    --
    Mike Meyer <> http://www.mired.org/consulting.html
    Independent Network/Unix/Perforce consultant, email for more information.
     
    Mike Meyer, Jan 9, 2008
    #15
  16. John Machin Guest

    On Jan 10, 7:34 am, "Reedick, Andrew" <> wrote:
    > > -----Original Message-----
    > > From: python-list-bounces+jr9445= [mailto:python-
    > > list-bounces+jr9445=] On Behalf Of John Machin
    > > Sent: Wednesday, January 09, 2008 3:02 PM
    > > To:
    > > Subject: Re: problem of converting a list to dict

    >
    > > On Jan 10, 6:52 am, "Reedick, Andrew" <> wrote:

    >
    > > > A bigger hint:
    > > > a=i.split('=')
    > > > print "'%s' splits into " % (i), a

    >
    > > consider:
    > > (1) using %r instead of '%s'

    >
    > Eh, personal preference depending on how sure you are of the
    > data's type.


    For a start, newbies should not assume that they know anything.
    Secondly, even if 100% sure that the object is a string object, using
    %r instead of '%s' greatly reduces the chance of confusion caused by
    content including tabs, newlines, apostrophes, non-ASCII characters,
    etc especially when there are e-mail and news clients adding noise to
    the channel.

    >
    > > (2) omitting the redundant space after 'into'

    >
    > Some of us coming in from other languages and still aren't used
    > to the comma adding an unwanted space after everything. I've been
    > tempted to root around in Python's source code to fix the problem.


    There are situations when the space is exactly what is wanted. In
    other situations where you need precise control, use file.write and %
    formatting. Here's a quick "macro" for retrofreaks:

    >>> def fprintf(stream, format, *varargs):

    .... stream.write(format % varargs)
    ....
    >>> import sys
    >>> fprintf(sys.stdout, "strg:%s int:%d\n", 'foo', 42)

    strg:foo int:42
    >>>



    >
    > > (3) losing the redundant () around i

    >
    > For me, the () is there for readability. Python's sprintf
    > syntax is odd to begin with, and something like
    > print "'%s' splits into " % i, a, b, c
    > means either
    > 1) you really do want to append b and c after the
    > sprintf, or
    > print "'%s' splits into " % (a), b, c
    > 2) that the formatting string is missing a few things
    > print "'%s' splits into " % (a, b, c) ## Ooops!
    > forgot to change it to "%s %5.2d %6.3f"
    >


    For readability, consider print ("'%s' splits into " % i), a, b, c
     
    John Machin, Jan 9, 2008
    #16
  17. bsneddon wrote:
    > This seemed to work for me if you are using 2.4 or greater and
    > like list comprehension.
    >>>> dict([ tuple(a.split("=")) for a in mylist[1:-1]])

    > {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}
    >
    > should be faster than looping


    That's what he's doing (well, a generator expression, not a listcomp).
    It's just split across multiple lines (ew).
    --
     
    Matt Nordhoff, Jan 9, 2008
    #17
    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. Skip Montanaro
    Replies:
    0
    Views:
    424
    Skip Montanaro
    Aug 15, 2003
  2. Alexander Kozlovsky

    dict!ident as equivalent of dict["ident"]

    Alexander Kozlovsky, May 21, 2006, in forum: Python
    Replies:
    5
    Views:
    368
    Alexander Kozlovsky
    May 22, 2006
  3. Paul Melis

    dict.has_key(x) versus 'x in dict'

    Paul Melis, Dec 6, 2006, in forum: Python
    Replies:
    48
    Views:
    1,338
    Kent Johnson
    Dec 15, 2006
  4. Almad
    Replies:
    8
    Views:
    416
    Terry Reedy
    Dec 14, 2006
  5. Drew
    Replies:
    19
    Views:
    1,360
    Duncan Booth
    Mar 15, 2007
Loading...

Share This Page