So I have a few csv files in in the following format:
person,age,nationality,language
Jack,18,Canadian,English
Rahul,25,Indian,Hindi
Mark,50,American,English
Kyou, 21, Japanese, English
I need to import that, and return that data as a dictionary, with the keys as the column headings in the first row, and all the data in each column as values for that specific key. For example:
dict = {
'person': ['Jack', 'Rahul', 'Mark', 'Kyou'],
'age': [18, 25, 50, 21],
'nationality': ['Canadian', 'Indian', 'American', 'Japanese'],
'language': ['English', 'Hindi', 'English', 'English']
}
Any idea how I would begin this code and make it so that the code would work for any number of columns given in a .csv file?
I'd go for something like:
Adapt accordingly.
You could use zipping combined with slicing in a dict comprehension, once you've gotten the data in to a list of lists with the csv module.
Here is a fairly straightforward solution that uses the python CSV module (DOCs here: http://docs.python.org/2/library/csv.html). Just replace 'csv_data.csv' with the name of you CSV file.
Using the csv module, I would do it this way: