RE: My Big Dict.

Discussion in 'Python' started by sismex01@hebmex.com, Jul 2, 2003.

  1. Guest

    > From: [mailto:p]
    > Sent: Miércoles, 02 de Julio de 2003 08:32 a.m.
    >
    > [...snippage...]
    >
    > d={}
    > for l in file("test.txt"):
    > try: i=l.index('!')
    > except ValueError: continue
    > d[l[:i]]=l[i+1:]
    >
    >


    This example is *almost* ideal; how about, instead of
    using .index and slices, let the computer do s'more
    of your work:


    D = {}
    for line in file("test.txt"):
    try:
    k,v = line.split("!",1)
    D[k] = v.strip()
    except ValueError:
    continue


    and presto. split() takes an optional second argument
    which specifies the maximum number of splits it's
    allowed to perform.

    Also, although I've kept your basic code form, it's
    bad style to not explicitly close any opened files,
    unless you absolutely know they're going to close
    once the operation finishes.

    -gustavo

    --
    Advertencia:La informacion contenida en este mensaje es confidencial y
    restringida, por lo tanto esta destinada unicamente para el uso de la
    persona arriba indicada, se le notifica que esta prohibida la difusion de
    este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
    la transmision, favor de comunicarse con el remitente. Gracias.
     
    , Jul 2, 2003
    #1
    1. Advertising

  2. > [...snippage...]
    >
    > d={}
    > for l in file("test.txt"):
    > try: i=l.index('!')
    > except ValueError: continue
    > d[l[:i]]=l[i+1:]
    >
    > [...snippage...]


    Just a little note : I generally try to avoid lowercase L and uppercase i as
    variable names, because in many fonts, there's barely any difference
    (sometimes none at all) between l and 1 and I (resp. lowercase L, number 1
    and capital i).

    For example : would you be able to find out what the result of the following
    code is just by looking at it? If you think you can, run it through python
    and see if you were right!

    l=1l
    I=1+l
    print l+l*I

    Cya,
    Aurélien
     
    Aurélien Géron, Jul 2, 2003
    #2
    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:
    426
    Skip Montanaro
    Aug 15, 2003
  2. Shaguf
    Replies:
    0
    Views:
    541
    Shaguf
    Dec 24, 2008
  3. Shaguf
    Replies:
    0
    Views:
    496
    Shaguf
    Dec 26, 2008
  4. Shaguf
    Replies:
    0
    Views:
    269
    Shaguf
    Dec 26, 2008
  5. Shaguf
    Replies:
    0
    Views:
    245
    Shaguf
    Dec 24, 2008
Loading...

Share This Page