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
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.
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".
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.
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 underlyingreader
instance...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With