I'm trying to make a csv file that contains a dictionary:
dict={"Steps" : [], "x" : []}
The problem is that the code of making csv is below and the data in "Steps" and "x" is this: Steps = {1, 2, 3, 4, 5, etc...}, x = {-1, 5, 2, 6, 73, 23, etc...} I want to separate those numbers by commas and write down those values in the columns under the variables (Steps, x) in csv.
Steps | x |
---|---|
1 | -1 |
2 | 5 |
3 | 2 |
5 | 6 |
etc. | etc. |
I've tried different things, like "delimiter" but didn't make everything right.
Can anyone help me?
def csvEXP(): #csv export
with open('RW_database.csv', 'w', encoding='UTF8') as csvfile:
writer = csv.DictWriter(csvfile, dict)
# write the header
writer.writeheader()
# write the data
for row in dict["Steps"]:
writer.writerow(dict)
Result of this code is this:
|Steps|x|
|-|-|
|{-1, 5, 2, 6, 73, 23, etc...}|{-1, 5, 2, 6, 73, 23, etc...}|
|{-1, 5, 2, 6, 73, 23, etc...}|{-1, 5, 2, 6, 73, 23, etc...}|
|{-1, 5, 2, 6, 73, 23, etc...}|{-1, 5, 2, 6, 73, 23, etc...}|
|{-1, 5, 2, 6, 73, 23, etc...}|{-1, 5, 2, 6, 73, 23, etc...}|
|etc.|etc.|
The WHOLE DICTIONARY.
CodePudding user response:
there is no need to make complex multi-level functions for this task. a simple loop and file I/O is sufficient:
dictionary = {"steps" : [1, 2, 3, 5], "x" : [-1, 5, 2, 6]}
file = open("data.csv", "w")
file.write("steps,x\n")
for index in range(len(dictionary["steps"])):
file.write(str(dictionary["steps"][index]) "," str(dictionary["x"][index]) "\n")
file.close()
CodePudding user response:
csv.DictWriter
could be useful if you would have list of dictionares
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)
But for your data you could use normal csv.writer
and 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)
Or you could use 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)