dictionary of list from a file

limodou limodou at gmail.com
Wed Oct 4 09:20:32 EDT 2006


On 4 Oct 2006 06:09:21 -0700, andrea.spitaleri at gmail.com
<andrea.spitaleri at gmail.com> wrote:
> Hi guys,
> this is my first post. my "programming" background is perlish scripting
> and now I am learning python. I need to create a dictionary of list
> from a file. Normally in perl I use to do like:
>
> while(<IN>){
>           @info=split(/ +/,$_);
>           push (@{$tmp{$info[0]}},$info[1]);
> }
>
> and then
> foreach $key (keys %tmp){
>            print "$key -> @{$tmp{$key}}\n";
> }
> i get
>
> 2 -> 1  2 3 4
> 7 -> 7 8 9 10
>
> in python I tried:
> b={}
> a=[]
> for line in fl.readlines():
>          info=lines.split()
>          b[info[0]] = a.append(info[1])
>
> and then
> for i in b:
>      print i,b[i]
> i get
> 2 None
> 7 None
>
> data file is:
> 2 1
> 2 2
> 2 3
> 2 4
> 7 7
> 7 8
> 7 9
> 7 10
>
> Any help??
> Thanks in advance
> Best Regards
>
> Andrea
>
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

Dict in Python has a setdefault method, if there is a key in dict,
it'll return the value, and if there is not a key existed, it'll
insert a key with the value supplied by the second parameter and
return the value. So using setdefault will be very handy for inserting
key.

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