dictionary of list from a file

sjdevnull at yahoo.com sjdevnull at yahoo.com
Wed Oct 4 16:11:15 EDT 2006


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.
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)




More information about the Python-list mailing list