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:
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:
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.
Csv.DictReader and csv.DictWriter. The class DictReader works in a similar manner as a csv.reader, but in Python 2 it maps the data to a dictionary and in Python 3 it maps data to an OrderedDict. The keys are given by the field-names parameter.
Can anyone help me with this?
EDITED Version 2:
Create a dictionary, then iterate over the result and stuff the rows in the dictionary. Note that if you encounter a row with a duplicate date, you will have to decide what to do (raise an exception, replace the previous row, discard the later row, etc...)
Here's test.csv:
and the corresponding program:
yields:
or, with DictReader:
results in:
Or perhaps you want to map the column headings to a list of values for that column:
That yields:
You need a Python DictReader class. More help can be found from here
Aamir AdnanAamir AdnanHelp from @phil-frost was very helpful, was exactly what I was looking for.
I have made few tweaks after that so I'm would like to share it here:
You can call it:
Where ref_colum will be your main key for each row.
Have you considered using Apache Solr? It supports search scoring and easily consumes CSV file data. You'll discover it scales impressively and has lots of other options for analysing your data, for example support for multiple languages or mis-spelled queries.
Examples
hi!
i want to place the contents of a dictionary into a csv file. Can someone help me with this?
i already have the code in reading the csv file
i want the first element of the row be the key for the dictionary so that if i access the dictionary again using the key i'll be able to get the different of the rows of that dictionary. I just don't know how to use loop thru the csv rows and put it in the dictionary and use the first element as a key.
for example: key name is key:
//key as the key
key first element of the row.
d = {'key': [1,2,3,4,5,6]}
//accessing the dictionary using key and were able to get the other elements of the row
d [1, 2, 3, 4, 5, 6]
can someone help me code this.
Thanks!