Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert csv data to dict

Tags:

I have csv file with following data

val1,val2,val3 1,2,3 22,23,33 

So how can I convert data into dict

dict1 = { 'val1': 1, 'val2': 2, 'val3': 3} dict2 = { 'val1': 22, 'val2': 23, 'val3': 33} fp = open('file.csv', 'r') reader = csv.reader(fp) for row in reader:     ???? 

Thanks

like image 204
laspal Avatar asked Mar 05 '10 15:03

laspal


People also ask

What does csv DictReader do?

The DictReader class allows you to create an object like a regular CSV reader. But it maps the information of each line to a dictionary ( dict ) whose keys are specified by the values of the first line. By using the DictReader class, you can access values in the country.

How do I convert a data table to a dictionary in Python?

First, search for the table header and split on spaces to define a list. Second, search for the virtual drive with "number/number" and split on spaces to define the second list. However, 'Size' will need to be special as it will need to ignore the space between number and "TB".

What does csv DictReader return?

The csv. DictReader() will return each row of type an OrederedDict, so we convert each OrderedDict type row to a dict using the type cast method. The object reader then displays all the data in the dictionary format, as shown in the above output.


2 Answers

import csv  reader = csv.DictReader(open('myfile.csv')) for row in reader:     # profit ! 
like image 171
Jimmy Avatar answered Sep 25 '22 17:09

Jimmy


Use csv.DictReader:

Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order. These elements become the keys of the resulting dictionary. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. If the row read has more fields than the fieldnames sequence, the remaining data is added as a sequence keyed by the value of restkey. If the row read has fewer fields than the fieldnames sequence, the remaining keys take the value of the optional restval parameter. Any other optional or keyword arguments are passed to the underlying reader instance...

like image 25
S.Lott Avatar answered Sep 24 '22 17:09

S.Lott