Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 CSV module and dictionary

Fairly new to python, forgive me if this is a basic question about learning how to use CSV files.

import csv
theReader = csv.reader(open('filename.csv'), delimiter=',')

for line in theReader:
    print line

So I've managed to open the file and can print it sprawling across my screen. But I'm trying to capture the data into Dictionaries.

This is example CSV:

Name,Age,Goals,Passes,Fouls  
Ted,21,1,20,1  
Ben,28,5,14,4  

I now need to create one dictionary with the headings in as the dictionary key (ideally skipping 'name'), then the dictionary values to be filled with the stats.

I'm then going to create another dictionary that has names:dates (dates I'm adding manually) as the key:value

Am I even right to be using the CSV mondule or should I be doing this via standar file type, and splitting lines by the comma?

like image 493
Zenettii Avatar asked Mar 08 '12 15:03

Zenettii


1 Answers

Python has a built-in library that handles reading your lines as dictionaries for you.

It is DictReader instead of reader.

http://docs.python.org/release/3.1.3/library/csv.html#csv.DictReader

Using this, each line would be a dictionary instead of a list.

Python 3

from csv import DictReader
the_reader = DictReader(open('filename.csv', 'r'))

for line_dict in the_reader:
  print(line_dict)
  # {'Name': 'Ted', 'Age': '21', 'Goals': '1', 'Passes': '20', 'Fouls': '1'}

Python 2

In Python 2, the mode is 'rb'.

the_reader = DictReader(open('filename.csv', 'rb'))
like image 121
dm03514 Avatar answered Nov 15 '22 01:11

dm03514