[Tutor] Writing dictionaries to a file

Jerrold Prothero jdprothero at gmail.com
Mon Apr 7 19:09:15 CEST 2008


I've been trying to understand how writing a dictionary to a file & reading
it back should work.

It's been suggested that if I had a clue, I'd use pickle, but since I
started
looking at the csv (comma separated values) module, which also supports
writing dictionaries out to a file, I at least wanted to understand how it's
supposed to work with csv.

Relevant Python 2.5 documentation sections are 9.1.1 and 9.1.4. My
question boils down to this: what does writerows want as an argument
for a dictionary?

Here's my set-up code (which executes without error)

from csv import *
d = {"a" : 1, "b" : 2}
f = open("test", "wb")
w = DictWriter(f, d.keys())  # Python docs 2.5, Section 9.1.1

Here are three guesses at how to call writerows, with error traces.

1)

w.writerows(d.items())

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    w.writerows(d.items())
  File "C:\Python25\lib\csv.py", line 129, in writerows
    rows.append(self._dict_to_list(rowdict))
  File "C:\Python25\lib\csv.py", line 118, in _dict_to_list
    for k in rowdict.keys():
AttributeError: 'tuple' object has no attribute 'keys'

2)

w.writerows(d)

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    w.writerows(d)
  File "C:\Python25\lib\csv.py", line 129, in writerows
    rows.append(self._dict_to_list(rowdict))
  File "C:\Python25\lib\csv.py", line 118, in _dict_to_list
    for k in rowdict.keys():
AttributeError: 'str' object has no attribute 'keys'

3)

w.writerows(d.iteritems())

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    w.writerows(d.iteritems())
  File "C:\Python25\lib\csv.py", line 129, in writerows
    rows.append(self._dict_to_list(rowdict))
  File "C:\Python25\lib\csv.py", line 118, in _dict_to_list
    for k in rowdict.keys():
AttributeError: 'tuple' object has no attribute 'keys'

>From Section 9.1.4 it looks like I'm supposed to do something with the
str() function, but I'm not sure what.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080407/2fc2dab6/attachment.htm 


More information about the Tutor mailing list