python - 将行写入 CSV 文件时为 "ValueError"

标签 python dictionary

writer = csv.DictWriter(result, fieldnames=Fnames)
for val in Fnames:
     for row in List:
          if str(row[1]) == str(val):
              dic = {str(val): row[2]}
              print dic.items()
              writer.writerows(dic)

我得到:

Error: ValueError: dict contains fields not in fieldnames: S, c, h, o, o, l

我正在将字典值写入 CSV 文件,但收到以下错误。我尝试过不同的方法但没有成功。我需要做什么才能将行写入 CSV?

最佳答案

Fnames 需要是要使用的字段名称的列表。看起来您已经向它传递了字符串“School”,并且它正在单独迭代每个字母。

检查here一些文档/示例。

关于python - 将行写入 CSV 文件时为 "ValueError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912189/

相关文章:

Python Argparse - 如何向默认帮助消息添加文本?

python - 异常处理: Differentiating between instances of the same error in Python

java - 自定义 equals() 方法无法正常工作

python - 如何从字典列表中获取字典的数据

c# - 将带有 List 的字典转换为 IEnumerable

python - 字符串列表列表到字典列表

python - 我应该如何在 Python 中逐行读取文件?

python - 支持向量机中无法使用奇怪的错误 “ValueError: ' x'来为numpy.random.RandomState实例播种?

python - 使用Beautiful Soup刮过YouTube验证徽章的实例吗?

json - 检查 map 是否在 Golang 中初始化