Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #4569 > unrolled thread
| Started by | "Alex van der Spek" <zdoor@xs4all.nl> |
|---|---|
| First post | 2011-05-03 21:50 +0200 |
| Last post | 2011-05-03 22:20 +0200 |
| Articles | 3 — 2 participants |
Back to article view | Back to comp.lang.python
Appending to dictionary of lists "Alex van der Spek" <zdoor@xs4all.nl> - 2011-05-03 21:50 +0200
Re: Appending to dictionary of lists Paul Rubin <no.email@nospam.invalid> - 2011-05-03 12:56 -0700
Re: Appending to dictionary of lists "Alex van der Spek" <zdoor@xs4all.nl> - 2011-05-03 22:20 +0200
| From | "Alex van der Spek" <zdoor@xs4all.nl> |
|---|---|
| Date | 2011-05-03 21:50 +0200 |
| Subject | Appending to dictionary of lists |
| Message-ID | <4dc05c8b$0$41117$e4fe514c@news.xs4all.nl> |
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
[toc] | [next] | [standalone]
| From | Paul Rubin <no.email@nospam.invalid> |
|---|---|
| Date | 2011-05-03 12:56 -0700 |
| Message-ID | <7x7ha75zib.fsf@ruckus.brouhaha.com> |
| In reply to | #4569 |
"Alex van der Spek" <zdoor@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.
[toc] | [prev] | [next] | [standalone]
| From | "Alex van der Spek" <zdoor@xs4all.nl> |
|---|---|
| Date | 2011-05-03 22:20 +0200 |
| Message-ID | <4dc06377$0$41110$e4fe514c@news.xs4all.nl> |
| In reply to | #4571 |
Thank you! Would never have found that by myself. "Paul Rubin" <no.email@nospam.invalid> wrote in message news:7x7ha75zib.fsf@ruckus.brouhaha.com... > "Alex van der Spek" <zdoor@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.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web