如何用逗号分割字典,并用Python制作正确的csv文件



我正在尝试制作一个包含字典的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
25
32
56

不需要为此任务制作复杂的多级函数。一个简单的循环和文件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.writerzip()

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)        

相关内容

  • 没有找到相关文章

最新更新