我有一个dict计数器列表,需要在csv中写入,但我无法解决问题。
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(t)
Result:
wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'int' object has no attribute 'keys'
我想要的是这样的csv:
name,count
dog,3
cat,5
DictWriter采用一系列映射,每个映射都必须具有与fieldnames
相同的密钥,因此需要[{"name": "dog", "count": 3}, ...]
修复t
:
rows = [{"name": name, "count": count} for name, count in t.items()]
然后将rows
传递给DictWriter.writerows()
,或者从一开始就生成正确的数据结构。