1

Possible Duplicate:
Creating a dictionary from a CSV file

I am having an issue when trying to print a dictionary to a CSV file. The dictionary currently has 4 columns but all 4 columns are printed in 1 single column. It may be the for loop that I am using to write to the CSV file is to blame but I am not quite sure. I am trying to have the dictionary print in each column.

Sample Data:

     Date        First Name     Last Name     Score
12/28/2012 15:15        John          Smith        20
12/29/2012 15:15        Alex          Jones        38
12/30/2012 15:15      Michael       Carpenter      25

Below are some code excerpts:

import csv

csvWriter = csv.writer(open("C:\\Users\\Chris\\Desktop\\test_out.csv", 'w'), delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)

For loop to read in CSV file above:

for row in reader:

for k, v in row.items():

    if not k in mydict:
        mydict[k] = [v]
    else:
        mydict[k].append(v)

For loop to print Dictionary keys to CSV file.

for item in mydict.keys():
    csvWriter.writerow(item)

Current output (column headings):

D a t e

F i r s t    N a m e

L a s t      N a m e

S c o r e

Wanted output (column headings):

Date      First Name       Last Name       Score

Any help would be greatly appreciated.

Community
  • 1
  • 1
gakar06
  • 313
  • 1
  • 4
  • 10
  • csvWriter.writerow(item) makes no sense. You are only writing one item per row... –  Jan 02 '13 at 18:25
  • Please read the writerow() docs. It it obvious that you need to pass all your column titles as a tuple to *one* writerow() call...this is basic datatype magic. –  Jan 02 '13 at 18:28
  • Do you know how i can change it so that it prints out in columns not rows? I would like it to read the CSV file in....do some calculations...and then print back out into a CSV file in the same format it came in as (if that makes sense). – gakar06 Jan 02 '13 at 18:30
  • If you are just trying to persist a dictionary on file (you seem to be writing it and reading it back again), I would not suggest using CSV. Instead look into just serializing and writing out the dictionary to a file, python has a very nice module called Shelve, which automates this process nicely: http://docs.python.org/2/library/shelve.html – Sanketh Katta Jan 02 '13 at 19:11
  • why are you using delimiter=' ' for a CSV file, shouldn't you want it to be delimiter=',' which is the default. – mhoran_psprep Jan 02 '13 at 19:15
  • @mhoran_psprep you are correct. At the time when i started this, it was printing everything with spaces...so i wanted to remove them but now after help from others on here, i can add that back in. Thanks! – gakar06 Jan 02 '13 at 19:19

2 Answers2

4

Now that I understand your structure better, try this:

#first write column headers
csvWriter.writerow(list(mydict.keys())

#now data, assuming each column has the same # of values
for i in xrange(len(mydict['Date'])):
    csvWriter.writerow([mydict[k][i] for k in mydict.keys()])
Cahlan Sharp
  • 793
  • 7
  • 9
  • @ Cahlan Sharp: I get an error when i try to do that. Traceback (most recent call last): File "C:\Users\Chris\Desktop\csv_reader3.py", line 32, in csvWriter.writerow(mydict.keys()) _csv.Error: sequence expected Not sure what the error means. – gakar06 Jan 02 '13 at 18:36
  • keys() will return an iterator, so you must wrap this into a list() call. –  Jan 02 '13 at 18:39
  • @ChrisPierce see latest edits, i'm not sure what your data structure looks like inside of your dict/list, but the given code should get you started. – Cahlan Sharp Jan 02 '13 at 18:48
  • @CahlanSharp When i try to print out the keys how you have it up above, i get an error with printing the keys to column. The error is " File "C:\Users\Chris\Desktop\csv_reader3.py", line 33, in csvWriter.writerow(list(mydict[0].keys())) KeyError: 0". Any ideas? – gakar06 Jan 02 '13 at 19:06
  • @ChrisPierce note that in my answer I'm using a list of dicts (mydata) rather than a single dict (mydict) as it appears that you're using. Are you using a single dict to hold all of the imported data? – Cahlan Sharp Jan 02 '13 at 19:19
  • @CahlanSharp Yes, currently it takes the first line of the CSV file as the key values (Date, First Name, Last Name, and Score) then creates lists for the values. So in the form of Date ['Date1','Date2',Date3',....]. I now want to go through the code and print out the keys in column form with the values correctly placed under each column key. If that makes sense. – gakar06 Jan 02 '13 at 19:26
  • @ChrisPierce then i think the latest edit should do it. – Cahlan Sharp Jan 02 '13 at 20:32
  • @CahlanSharp Excellent, that worked! Thanks! Only other question i have is now the output places an extra return in between each line. Do you know how to remove that? – gakar06 Jan 02 '13 at 20:51
  • @CahlanSharp Nvm about the question. I found that if I added **lineterminator='\n'** to the CSV write function **csvWriter = csv.writer(open("C:\\Users\\Chris\\Desktop\\test_out.csv", 'w'), delimiter=',', lineterminator='\n')** that it would remove the extra line spaces. I tried making the write function binary (adding 'wb' instead of 'w') but I kept getting _TypeError: Str does not support buffer interface_ error messages. Thanks for your help again! – gakar06 Jan 03 '13 at 05:30
1

Python 2:

csvWriter.writerow(mydict.keys())

Python 3:

csvWriter.writerow(list(mydict.keys()))