python - CSV、Python : Using DictWriter correctly (ValueError: dict contains fields not in fieldnames)

标签 python csv unicode dictionary

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

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)

所以我传入了我的对象实例。 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'}

所以我真的想要第一排:

stuff stuff stuff stuff stuff

我的印象是 writerow 通过提供的字典,使用提供的 dictwriter 字段名调用提供的字典的键名,并输出值。

相反,我得到:

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

我现在只是不明白这一点。它使用常规 Python csv 库和我发现的 unicode csv 库来执行此操作。谁能解释一下这是什么问题?

最佳答案

您需要 writerow 而不是 writerows

前者接受一个参数,即要写入的行。后者采用可迭代的行。您正在使用字典调用 writerows,它会尝试遍历字典并写入每个条目。由于迭代字典给出了它们的键,这与调用 writerow(n6s2f0e1) 相同,后者(显然)失败并出现您看到的错误。

关于python - CSV、Python : Using DictWriter correctly (ValueError: dict contains fields not in fieldnames),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13367732/

相关文章:

Python:如何从FASTA文件中的滑动窗口打印长度为n的序列?

java - OCSP命令行测试工具?

java - OpenCsv 用 BeanToCsv + HeaderColumnNameTranslateMappingStrategy 写错列名

VBA使用登录名和密码从网站下载csv文件

c++ - QByteArray 到 QBitArray 到 QbyteArray 到 QString + Unicode 字符

c++ - 上标的 Unicode 字符显示方框 : ࠚ

python - pip 未被识别为内部或外部命令

python - 是否应该在 cython 中定义列表项类型?

python - 通过使用 python 和 pandas 使用 2 个现有列的函数填充新列

python - urllib.request 中的 Unicode 字符串