Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a CSV file with dict keys as column names

Tags:

python

file

csv

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?

like image 609
user1487000 Avatar asked Dec 09 '22 17:12

user1487000


1 Answers

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'}]
like image 70
Claudio Avatar answered Dec 11 '22 08:12

Claudio