我正在尝试制作一个包含字典的csv文件:
dict={"Steps" : [], "x" : []}
问题是制作csv的代码在下面;步骤";以及";x〃;是这样的吗:步骤={1,2,3,4,5,etc.…},x={-1,5,2,6,73,23,etc...}我想用逗号分隔这些数字,并将这些值写在csv中变量(Steps,x(下的列中。
步骤 | x |
---|---|
1 | -1 |
2 | 5 |
3 | 2 |
5 | 6 |
等 | 等 |
不需要为此任务制作复杂的多级函数。一个简单的循环和文件I/O就足够了:
dictionary = {"steps" : [1, 2, 3, 5], "x" : [-1, 5, 2, 6]}
file = open("data.csv", "w")
file.write("steps,xn")
for index in range(len(dictionary["steps"])):
file.write(str(dictionary["steps"][index]) + "," + str(dictionary["x"][index]) + "n")
file.close()
csv.DictWriter
如果您有字典的列表,可能会很有用
import csv
data = [
{"Steps": 1, "x": -1 },
{"Steps": 2, "x": 5 },
{"Steps": 3, "x": 2 },
{"Steps": 4, "x": 6 },
{"Steps": 5, "x": 73 },
]
headers = ['Steps','x']
with open('RW_database.csv', 'w', encoding='UTF8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
for row in data:
writer.writerow(row)
但对于您的数据,您可以使用普通的csv.writer
和zip()
import csv
data = {
"Steps" : [1, 2, 3, 4, 5],
"x" : [-1, 5, 2, 6, 73]
}
headers = ['Steps','x']
with open('RW_database.csv', 'w', encoding='UTF8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
for row in zip(data['Steps'], data['x']):
writer.writerow(row)
或者你可以使用pandas.DataFrame
import pandas as pd
data = {
"Steps" : [1, 2, 3, 4, 5],
"x" : [-1, 5, 2, 6, 73]
}
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)