Populating a dictionary, fast

DouhetSukd DouhetSukd at gmail.com
Sun Nov 11 10:49:40 EST 2007


On Nov 11, 7:35 am, Michael Bacarella <m... at gpshopper.com> wrote:

> Tried that already.  No difference. :(

Not sure if it would make a difference, and it would imply re-
organizing your preceding lines, but what about doing the dictionary
build in one go, rather than incrementally?  Using the dict function,
which takes a list of (key,value) tuples.  I use it frequently as a
space-saver and it works well enough.  It may speed things up, I
dunno.  I had to break out your formatting in its own function and
that can't help too much.

Something like:

def fmt(line):
    id,name = line.strip().split(':')
    id = long(id)
    return (id,name)

id2name = dict([fmt(line) for line in
iter(open('id2name.txt').readline,'')])

Cheers




More information about the Python-list mailing list