dictionary of list from a file

Giovanni Bajo raNOsky at deveSPAMler.com
Wed Oct 4 16:16:48 CEST 2006


andrea.spitaleri at gmail.com wrote:

> while(<IN>){
>           @info=split(/ +/,$_);
>           push (@{$tmp{$info[0]}},$info[1]);
> }
>
> and then
> foreach $key (keys %tmp){
>            print "$key -> @{$tmp{$key}}\n";
> }

Python 2.5 introduced a dictionary type with automatic creation of values,
ala Perl:

===============================
from collections import defaultdict

d = defaultdict(list)
for line in fl:
     k, v = line.strip().split()
     d[k].append(v)

for k,v in d.items():
     print k, v
===============================

Notice that Python is always more strongly typed, so you have to specify a
factory function.
-- 
Giovanni Bajo





More information about the Python-list mailing list