CSV, Python: using DictWriter correctly (ValueError: dict contains fields not in field names)

I'm having difficulty grabbing DictWriter in the csv module (Python 2.7). I have this (oh, and I use the unicodecsv library because I read that there are problems):

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 am passing an instance of an object. f:

 [u'n6s2f0e1', u'n1s0f0e0', u'n2s0f0e1', u'n3s1f0e0', u'n5s2f0e0', u'n4s1f0e1'] 

object_instance.return_a_dictionary:

 {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 I really want the first line:

 stuff stuff stuff stuff stuff 

I get the impression that writerow goes through the provided dictionary, names the key name of the provided dict with the provided names of the recorder and displays 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 do not understand this at the moment. It does this with both the regular Python csv library and the unicode csv library I found. Can anyone explain what the problem is?

+4
source share
1 answer

You want writerow not writerows .

The first takes a single argument, which is the string to be written. The latter accepts iterable strings. You call writerows with a dictionary that tries to writerows over the dictionary and write each entry. Since dicts iteration gives its keys, it is the same as calling writerow(n6s2f0e1) , which (obviously) does not work with the error you see.

+13
source

Source: https://habr.com/ru/post/1445849/


All Articles