I am in the process of trying to write a python script that will take input from a CSV file and then push it into a dictionary format (I am using Python 3.x).
I use the code below to read in the CSV file and that works:
import csv
reader = csv.reader(open('C:\\Users\\Chris\\Desktop\\test.csv'), delimiter=',', quotechar='|')
for row in reader:
print(', '.join(row))
But now I want to place the results into a dictionary. I would like the first row of the CSV file to be used as the "key" field for the dictionary with the subsequent rows in the CSV file filling out the data portion.
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
There are additional things I would like to do with this code but for now just getting the dictionary to work is what I am looking for.
Can anyone help me with this?
EDITED Version 2:
import csv
reader = csv.DictReader(open('C:\\Users\\Chris\\Desktop\\test.csv'))
result = {}
for row in reader:
for column, value in row.items():
result.setdefault(column, []).append(value)
print('Column -> ', column, '\nValue -> ', value)
print(result)
fieldnames = result.keys()
csvwriter = csv.DictWriter(open('C:\\Users\\Chris\\Desktop\\test_out.csv', 'w'), delimiter=',', fieldnames=result.keys())
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
for row in result.items():
print('Values -> ', row)
#csvwriter.writerow(row)
'''
Test output
'''
test_array = []
test_array.append({'fruit': 'apple', 'quantity': 5, 'color': 'red'});
test_array.append({'fruit': 'pear', 'quantity': 8, 'color': 'green'});
test_array.append({'fruit': 'banana', 'quantity': 3, 'color': 'yellow'});
test_array.append({'fruit': 'orange', 'quantity': 11, 'color': 'orange'});
fieldnames = ['fruit', 'quantity', 'color']
test_file = open('C:\\Users\\Chris\\Desktop\\test_out.csv','w')
csvwriter = csv.DictWriter(test_file, delimiter=',', fieldnames=fieldnames)
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
for row in test_array:
print(row)
csvwriter.writerow(row)
test_file.close()
[Date, First Name, Last Name, Score]
and each entry is a list of all the items in the corresponding column. but i have a feeling you mean you want the date on each row to be the key, and then have[First Name, Last Name, Score]
as the values. - Inbar Rose'C:/Users/Chris/Desktop/test.csv'
. It works fine in Windows. Alternatively, you can use a raw string where escape sequences are not interpreted (hence no doubling the backslash) --r'C:\Users\Chris\Desktop\test.csv'
. - pepr