Appending to dictionary of lists

Dan Stromberg drsalists at gmail.com
Tue May 3 16:16:09 EDT 2011


On Tue, May 3, 2011 at 12:56 PM, Paul Rubin <no.email at nospam.invalid> wrote:

> "Alex van der Spek" <zdoor at xs4all.nl> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Agreed.  Here's another way: using a dictionary comprehension - a feature in
2.7 and up:

#!/usr/local/cpython-2.7/bin/python

import csv
import pprint

csvf=open('foo.csv','rb')
csvr=csv.DictReader(csvf)
#refd=dict.fromkeys(csvr.fieldnames, [])
refd = { key: [] for key in csvr.fieldnames }
for row in csvr:
   for (k,v) in row.items():
      refd[k].append(v)

pprint.pprint(refd)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110503/a141d325/attachment-0001.html>


More information about the Python-list mailing list