dictionary of list from a file

Matthew Warren Matthew.Warren at Digica.com
Thu Oct 5 09:28:46 EDT 2006


 

> -----Original Message-----
> From: 
> python-list-bounces+matthew.warren=digica.com at python.org 
> [mailto:python-list-bounces+matthew.warren=digica.com at python.o
> rg] On Behalf Of Giovanni Bajo
> Sent: 04 October 2006 15:17
> To: python-list at python.org
> Subject: Re: dictionary of list from a file
> 
> 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.


Yay! Python2.5 fixed my approach to this, I tried

from collections import defaultdict
f=file('c:\\test.txt')
lines=f.readlines()
f.close()
d=defaultdict(list)
[ d[l.split()[0]].append(l.split()[1]) for l in lines ]

But, if I try your (to see if I've actually got it right)

For k,v in d.items():
	print k,v

I get

AttributeError: 'list' object has no attribute 'items'




This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. 

You should not copy the email, use it for any purpose or disclose its contents to any other person.
Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com



More information about the Python-list mailing list