dictionary of list from a file

limodou limodou at gmail.com
Wed Oct 4 21:59:08 EDT 2006


On 4 Oct 2006 13:11:15 -0700, sjdevnull at yahoo.com <sjdevnull at yahoo.com> wrote:
> limodou wrote:
> > here is my program
> >
> > d = {}
> > for line in file('test.txt'):
> >     line = line.strip()
> >     if line:
> >         k, v = line.strip().split()
> >         d.setdefault(k, []).append(v)
> > print d
>
> Minor nits: you call strip twice, when you don't need to.  just omit
> the second call.

Yes, I forgot that.

> Also, I'm not sure stripping the line is the right thing per the spec;
>
> d = {}
> for line in [l[:-1] for l in file('test.txt', 'rU') if len(l)>1]:
>     k,v = line.split()
>     d.setdefault(k,[]).append(v)
>
[l[:-1] for l in file('test.txt', 'rU') if len(l)>1]

this line I think will create a list, and if the file is large, it'll
consume many memory I think.

And I think using strip is more clear than list comprehension, except
for the memory consume.

-- 
I like python!
UliPad <<The Python Editor>>: http://wiki.woodpecker.org.cn/moin/UliPad
My Blog: http://www.donews.net/limodou



More information about the Python-list mailing list