Python3 CSV module and dictionary

Pretty new to python, forgive me if this is the main 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 managed to open the file and print it on my screen. But I'm trying to write data to dictionaries.

This is a CSV example:

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

Now I need to create one dictionary with headings as a dictionary key (ideally skipping the "name"), and then the dictionary values ​​that will be filled with statistics.

Then I will create another dictionary with names: dates (dates that I add manually) as a key: value

Am I even right to use the CSV schedule, or should I do it through a standard file and separate the lines with a comma?

+4
source share
1 answer

Python has a built-in library that treats your strings as dictionaries for you.

This is a DictReader instead of a reader .

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

Using this, each line will be a dictionary, not 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 'rb' mode.

 the_reader = DictReader(open('filename.csv', 'rb')) 
+11
source

Source: https://habr.com/ru/post/1400399/


All Articles