You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用csv.DictWriter写入Counter数据报AttributeError错误的技术咨询

解决Counter写入CSV的AttributeError问题

错误原因

csv.DictWriter.writerows()要求传入的可迭代对象中,每个元素必须是匹配fieldnames的字典。但直接传入Counter对象时,迭代得到的是字典的键(字符串),若误传值则会得到整数,这些类型都不符合DictWriter的要求,因此触发AttributeError。

解决方案

方法一:用列表推导式转换为字典列表

将Counter的键值对转换成符合fieldnames格式的字典列表,直接传给writerows():

import csv
from collections import Counter

t = Counter({'dog': 3, 'cat': 5})

with open('test.csv', 'w', encoding='utf8', newline="") as output_file:
    fieldnames = ["name", "count"]
    dict_writer = csv.DictWriter(output_file, fieldnames=fieldnames)
    dict_writer.writeheader()
    # 将键值对转换为指定格式的字典
    dict_writer.writerows([{'name': key, 'count': value} for key, value in t.items()])

方法二:循环逐个写入行

通过循环遍历Counter的键值对,用writerow()逐行写入:

import csv
from collections import Counter

t = Counter({'dog': 3, 'cat': 5})

with open('test.csv', 'w', encoding='utf8', newline="") as output_file:
    fieldnames = ["name", "count"]
    dict_writer = csv.DictWriter(output_file, fieldnames=fieldnames)
    dict_writer.writeheader()
    # 遍历键值对,逐个写入
    for name, count in t.items():
        dict_writer.writerow({'name': name, 'count': count})

两种方法都能生成你期望的CSV格式:

name,count
dog,3
cat,5

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:05:25