python – Best way to convert csv data to dict

python – Best way to convert csv data to dict

import csv

reader = csv.DictReader(open(myfile.csv))
for row in reader:
    # profit !

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…

python – Best way to convert csv data to dict

The cool thing with using csv as mentioned in other answers here is that it can be used for reading a file (the obvious use case) but also parse a regular csv formatted string.

Example for reading a csv file:

import csv
with open(my_file.csv) as f:
   for line in csv.DictReader(f, fieldnames=(val1, val2, val3)):
      print(line)

notice that you can explicitly pass the headers which you want be the keys, making it very easy to use csv files without headers.

Another use case is reading just a regular string with csv

Example:

import csv
my_csv_string = val1, val2, val3
my_csv_dict = next(csv.DictReader(StringIO(s), fieldnames=(key1, key2, key3)))

Anyway, csv.DictReader() is what you need..

Leave a Reply

Your email address will not be published. Required fields are marked *