By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,818 Members | 1,223 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,818 IT Pros & Developers. It's quick & easy.

How to create csv file format using the list of dictionaries

P: 8
Hi all,

Further to my 'list of dictionaries' question yesterday, I would to ask how to write data to csv file format using 'list of dictionaries' as a source:

data to be written to .csv file:
dictList = [ {'FirstName': 'Michael', 'LastName': 'Kirk', 'SSID': '224567'},
{'FirstName': 'Linda', 'LastName': 'Matthew', 'SSID': '123456'},
{'FirstName': 'Sandra', 'LastName': 'Parkin', 'SSID': '123456'},
{'FirstName': 'Bob', 'LastName': 'Henry', 'SSID': '666666'},
{'FirstName': 'Silvia', 'LastName': 'Perkin', 'SSID': '676767'}]

so the csv file would look something like:
Michael,Kirk,224567
Linda,Matthew,123456
Sandra,Parkin,123456
Bob,Henry,666666
Silvia,Perkin,676767

What I have in mind for the code would be something like this:

import csv

dictList = [ {'FirstName': 'Michael', 'LastName': 'Kirk', 'SSID': '224567'},
{'FirstName': 'Linda', 'LastName': 'Matthew', 'SSID': '123456'},
{'FirstName': 'Sandra', 'LastName': 'Parkin', 'SSID': '123456'},
{'FirstName': 'Bob', 'LastName': 'Henry', 'SSID': '666666'},
{'FirstName': 'Silvia', 'LastName': 'Perkin', 'SSID': '676767'}]

writer = csv.writer(file('csv_test.CSV','wb'))

for item in dictList:
writer.writerow(item['FirstName'],item['LastName'],item['SSID'])


I am not sure whether it will work out well, but any suggestion(s)/comment(s) are welcomed.

Thanks!
Mar 12 '08 #1
Share this Question
Share on Google+
3 Replies


jlm699
100+
P: 314
You're on the right track.. I've never used the csv module however, as I find it just as easy to do the following:
Expand|Select|Wrap|Line Numbers
  1. fh = open('csvTest.csv', 'wb')
  2.  
  3. for elem in dictList:
  4.     fh.write('%s,%s,%s\n' % (elem['FirstName'], elem['LastName'], elem['SSID']
  5.  
  6. fh.close()
But there is nothing wrong with using the CSV module, I've just never used it myself. You are on the right track though.
Mar 12 '08 #2

bvdet
Expert Mod 2.5K+
P: 2,851
I agree with jlm699 (he's pretty sharp). I have never used the csv module either since most of my applications are simple. Here's some more sample code:
Expand|Select|Wrap|Line Numbers
  1. output = [','.join((item['FirstName'], item['LastName'], item['SSID'])) for item in dictList]
  2. f = open('output.csv', 'w')
  3. f.write('\n'.join(output))
  4. f.close()
Mar 12 '08 #3

P: 8
Ah Ok,

I agree with you guys, will prefer simpler method, of course.

Thanks!
Mar 12 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.