Creating a dictionary from a csv file?

后端 未结 16 2321
北荒
北荒 2020-11-22 06:13

I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file rep

16条回答
  •  眼角桃花
    2020-11-22 06:22

    Open the file by calling open and then csv.DictReader.

    input_file = csv.DictReader(open("coors.csv"))
    

    You may iterate over the rows of the csv file dict reader object by iterating over input_file.

    for row in input_file:
        print(row)
    

    OR To access first line only

    dictobj = csv.DictReader(open('coors.csv')).next() 
    

    UPDATE In python 3+ versions, this code would change a little:

    reader = csv.DictReader(open('coors.csv'))
    dictobj = next(reader) 
    

提交回复
热议问题