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!
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to