I’m having difficulties grasping the DictWriter in the csv module (Python 2.7). I have this (oh, and I’m using a unicodecsv library because I’ve read there are issues):
f = object_instance.return_a_dictionary.keys()
with open('eggs.csv', 'wb') as csvfile:
spamwriter = unicodecsv.DictWriter(csvfile, fieldnames=f)
spamwriter.writerows(object_instance.return_a_dictionary)
So I pass in my object instance. f is:
[u'n6s2f0e1', u'n1s0f0e0', u'n2s0f0e1', u'n3s1f0e0', u'n5s2f0e0', u'n4s1f0e1']
object_instance.return_a_dictionary is:
{u'n6s2f0e1': u'stuff', u'n1s0f0e0': u'stuff', u'n2s0f0e1': u'stuff', u'n3s1f0e0': u'stuff', u'n5s2f0e0': u'stuff', u'n4s1f0e1': u'stuff'}
So really I want a first row:
stuff stuff stuff stuff stuff
I’m under the impression that writerow goes through the provided dictionary, calls the keyname of the provided dict with the dictwriter fieldnames provided, and outputs the value.
Instead I get:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/usr/lib/python2.7/csv.py", line 153, in writerows
rows.append(self._dict_to_list(rowdict))
>>> File "/usr/lib/python2.7/csv.py", line 144, in _dict_to_list
", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: n, 6, s, 2, f, 0, e, 1
I just don’t understand this at this point. It does this with both the regular Python csv library and a unicode csv library I’ve found. Can anyone explain what the issue is?
You want
writerownotwriterows.The former takes a single argument, which is the row to be written. The latter takes an iterable of rows. You are calling
writerowswith a dictionary, which tries to iterate over the dictionary and write each entry. Since iterating over dicts gives their keys, this is the same as callingwriterow(n6s2f0e1)which (obviously) fails with the error you see.