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
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...
import csv
reader = csv.DictReader(open('myfile.csv'))
for row in reader:
# profit !
Oftentimes I feel like upgrading to pandas while manipulating CSVs. It gives you a whole new world of possibilities.
import pandas as pd
df=pd.read_csv('test.csv')
for index, row in df.iterrows():
d=row.to_dict()
print(d)
print("")
print( df[df.val3>10].iloc[0].to_dict() )
print( list(df[['val3']]['val3']) )
Output:
{'val1': 1, 'val2': 2, 'val3': 3}
{'val1': 22, 'val2': 23, 'val3': 33}
{'val1': 22, 'val2': 23, 'val3': 33}
[3, 33]
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..