My Big Dict.

sismex01 at hebmex.com sismex01 at hebmex.com
Wed Jul 2 18:05:29 CEST 2003


> From: psimmo60 at hotmail.com [mailto:psimmo60 at hotmail.com] 
> 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.





More information about the Python-list mailing list