Appending to dictionary of lists

  • Thread starter Alex van der Spek
  • Start date
A

Alex van der Spek

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
 
P

Paul Rubin

Alex van der Spek said:
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.
 
A

Alex van der Spek

Thank you! Would never have found that by myself.


Paul Rubin said:
Alex van der Spek said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top