My Big Dict.

Paul Simmonds psimmo60 at
Thu Jul 3 13:32:21 CEST 2003

Christian Tismer <tismer at> wrote in message news:<mailman.1057162092.18394.python-list at>...
> Paul Simmonds wrote:
> ...
> I'm not trying to intrude this thread, but was just
> struck by the list comprehension below, so this is
> about readability.
> >
> > d=dict([(l[:l.index('!')],l[l.index('!')+1:-1])\
> >        for l in file('test.txt') if l.count('!')])
> With every respect, this looks pretty much like another
> P-language. The pure existance of list comprehensions
> does not try to force you to use it everywhere :-)

Quite right. I think that mutation came from the fact that I was
thinking in C all day. Still, I don't even write C like
should be put to sleep ASAP.

> > d={}
> > for l in file("test.txt"):
> >     try: i=l.index('!')
> >     except ValueError: continue
> >     d[l[:i]]=l[i+1:]
> About speed: I'm not sure with the current Python
> version, but it might be worth trying to go without
> the exception:
> d={}
> for l in file("test.txt"):
>      i=l.find('!')
>      if i >= 0:
>          d[l[:i]]=l[i+1:]
> and then you might even consider to split on the first
> "!", but I didn't do any timings:
> d={}
> for l in file("test.txt"):
>      try:
>          key, value = l.split("!", 1)
>      except ValueError: continue
>      d[key] = value
Just when you think you know a language, an optional argument you've
never used pops up to make your life easier. Thanks for pointing that

I've done some timings on the functions above, here are the results:

Python2.2.1, 200000 line file(all data lines)
try/except with split:   3.08s
    if     with slicing: 2.32s
try/except with slicing: 2.34s

So slicing seems quicker than split, and using if instead of
try/except appears to speed it up a little more. I don't know how much
faster the current version of the interpreter would be, but I doubt
the ranking would change much.


More information about the Python-list mailing list