我有以下代码,我正在尝试将字典的内容写入CSV文件。
import csv
my_dict = {
"Power outage": 3,
"System overload": 3,
"Pasta not aldente": 3,
"No internet": 2,
"No red marker": 1,
}
with open("testCsv.csv", "w", newline="") as file:
fieldnames = ["Type", "Count"]
writer = csv.DictWriter(file, delimiter=",", fieldnames=fieldnames)
writer.writeheader()
for k, v in my_dict.items():
writer.writerow({my_dict[k], my_dict[v]})
file.close()
运行文件时,出现以下错误,无法在线找到任何答案或提示。
Traceback (most recent call last):
File "csvWrite.py", line 17, in <module>
writer.writerow({my_dict[k], my_dict[v]})
KeyError: 3
Make sure you iterate correctly through the
my_dict
and assign key-value pairs before writing to CSV.Can you change the line
writer.writerow({my_dict[k], my_dict[v]})
withwriter.writerow({"Type": k, "Count": v})
. I guess you are tried to access 3 (on the first line) which is the value of "Power outage" but not presents in my_dict keys. You also don't need to addfile.close()
with
statement handles it.