我有這個需要在 csv 中寫入的 dict 計數器串列,但我無法找出問題所在。
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
uj5u.com熱心網友回復:
DictWriter 采用一系列映射,每個映射都必須具有相同的鍵fieldnames- 所以你需要[{"name": "dog", "count": 3}, ...]
修復t:
rows = [{"name": name, "count": count} for name, count in t.items()]
然后傳遞rows給DictWriter.writerows(),或者從一開始就生成正確的資料結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/523228.html
標籤:PythonCSV
下一篇:如何編輯CSV檔案中的資料?
