Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Appending to dictionary of lists

Reply
Thread Tools

Appending to dictionary of lists

 
 
Alex van der Spek
Guest
Posts: n/a
 
      05-03-2011
I open a csv file and create a DictReader object. Subsequently, reading
lines from this file I try to update a dictionary of lists:

csvf=open(os.path.join(root,fcsv),'rb')
csvr=csv.DictReader(csvf)
refd=dict.fromkeys(csvr.fieldnames,[])
for row in csvr:
for (k,v) in row.items():
refd[k].append(v)

I do not understand why this appends v to every key k each time.

Thanks in advance for any tips you can pass on.

Alex van der Spek

 
Reply With Quote
 
 
 
 
Paul Rubin
Guest
Posts: n/a
 
      05-03-2011
"Alex van der Spek" <(E-Mail Removed)> writes:
> refd=dict.fromkeys(csvr.fieldnames,[]) ...
> I do not understand why this appends v to every key k each time.


You have initialized every element of refd to the same list. Try

refd = dict((k,[]) for k in csvr.fieldnames)

instead.
 
Reply With Quote
 
 
 
 
Alex van der Spek
Guest
Posts: n/a
 
      05-03-2011
Thank you! Would never have found that by myself.


"Paul Rubin" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> "Alex van der Spek" <(E-Mail Removed)> writes:
>> refd=dict.fromkeys(csvr.fieldnames,[]) ...
>> I do not understand why this appends v to every key k each time.

>
> You have initialized every element of refd to the same list. Try
>
> refd = dict((k,[]) for k in csvr.fieldnames)
>
> instead.


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Performance ordered dictionary vs normal dictionary Navkirat Singh Python 6 07-29-2010 10:18 AM
creating a dictionary from a dictionary with regex james_027 Python 1 08-22-2007 07:39 AM
creating and appending to a dictionary of a list of lists pyscottishguy@hotmail.com Python 2 08-15-2007 12:57 PM
List of lists of lists of lists... =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?= Python 5 05-15-2006 11:47 AM
[DICTIONARY] - Copy dictionary entries to attributes Ilias Lazaridis Python 6 02-21-2006 11:27 AM



Advertisments