CSV,Python:正确使用DictWriter(ValueError:dict包含字段名中未包含的字段)

CSV,Python:正确使用DictWriter(ValueError:dict包含字段名中未包含的字段),python,csv,unicode,dictionary,Python,Csv,Unicode,Dictionary,我很难掌握csv模块(Python 2.7)中的DictWriter。我有这个(哦,我正在使用Unicodesv库,因为我读到有问题): 所以我传入我的对象实例。f是: [u'n6s2f0e1', u'n1s0f0e0', u'n2s0f0e1', u'n3s1f0e0', u'n5s2f0e0', u'n4s1f0e1'] object\u instance.return\u字典是: {u'n6s2f0e1': u'stuff', u'n1s0f0e0': u'stuff', u'n2s0f

我很难掌握csv模块(Python 2.7)中的DictWriter。我有这个(哦,我正在使用Unicodesv库,因为我读到有问题):

所以我传入我的对象实例。f是:

[u'n6s2f0e1', u'n1s0f0e0', u'n2s0f0e1', u'n3s1f0e0', u'n5s2f0e0', u'n4s1f0e1']
object\u instance.return\u字典是:

{u'n6s2f0e1': u'stuff', u'n1s0f0e0': u'stuff', u'n2s0f0e1': u'stuff', u'n3s1f0e0': u'stuff', u'n5s2f0e0': u'stuff', u'n4s1f0e1': u'stuff'}
所以我真的想要第一排:

stuff stuff stuff stuff stuff
我的印象是writerow遍历提供的字典,使用提供的dictwriter字段名调用提供的dict的键名,并输出值

相反,我得到:

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
回溯(最近一次呼叫最后一次):
文件“”,第3行,在
writerows中的文件“/usr/lib/python2.7/csv.py”,第153行
行。追加(self.\u dict\u to\u list(rowdict))
>>>文件“/usr/lib/python2.7/csv.py”,第144行,在目录列表中
“,”.join(错误的_字段))
ValueError:dict包含不在字段名中的字段:n、6、s、2、f、0、e、1

我只是不明白这一点。它通过我找到的常规Python csv库和unicode csv库实现了这一点。有人能解释一下问题是什么吗?

你想要的是
writerow
而不是
writerows


前者接受单个参数,即要写入的行。后者需要一系列行。您正在使用字典调用
writerows
,该字典尝试在字典上迭代并写入每个条目。由于迭代dicts给出了它们的键,这与调用
writerow(n6s2f0e1)
是一样的,它(显然)失败了,出现了您看到的错误。

,但至少我将来能够区分。仅供参考,我的计算方法是将字段解释为n,6这意味着它将字符串
“n6s2f0e1”
作为行而不是键进行迭代。从那开始解释就很简单了。我知道它是因为某种原因把它拆开的,但是第一次我实际上已经开始使用csv模块了,所以我不知道。
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