I have data in the format of dicts as follows:
{Color: Red, Age: 29, Date: October 2nd, Time: 4pm}
And I want to write these dicts to a csv in such a way that the "Color, age, date, time" are the column titles, and the fields get filed in as the rows. That way, when I read the csv file again, I get the data formatted in the same way mentioned above.
What is the proper way to go about this?
Using the standard csv module you can use DictWriter and DictReader classes for achieving what you want.
for writing:
import csv
dics = [{'Color':'Red', 'Age':29, 'Date':'October 2nd', 'Time':'4pm'},
{'Color':'Blue', 'Age':32, 'Date':'December 5th', 'Time':'6pm'},
{'Color':'Green', 'Age':12, 'Date':'January 10th', 'Time':'2pm'}]
with open("file.csv",'wb') as f:
# Using dictionary keys as fieldnames for the CSV file header
writer = csv.DictWriter(f, dics[0].keys())
writer.writeheader()
for d in dics:
writer.writerow(d)
for reading:
import csv
with open("file.csv", 'rb') as f:
reader = csv.DictReader(f)
dics = [ d for d in reader ]
>>> dics
[{'Color': 'Red', 'Date': 'October 2nd', 'Age': '29', 'Time': '4pm'},
{'Color': 'Blue', 'Date': 'December 5th', 'Age': '32', 'Time': '6pm'},
{'Color': 'Green', 'Date': 'January 10th', 'Age': '12', 'Time': '2pm'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With