Best way to convert csv data to dict

后端 未结 4 1739
眼角桃花
眼角桃花 2021-01-03 22:07

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         


        
4条回答
  •  清歌不尽
    2021-01-03 22:41

    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..

提交回复
热议问题