Creating a dictionary from a csv file?

后端 未结 16 2259
北荒
北荒 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:16

    I believe the syntax you were looking for is as follows:

    import csv
    
    with open('coors.csv', mode='r') as infile:
        reader = csv.reader(infile)
        with open('coors_new.csv', mode='w') as outfile:
            writer = csv.writer(outfile)
            mydict = {rows[0]:rows[1] for rows in reader}
    

    Alternately, for python <= 2.7.1, you want:

    mydict = dict((rows[0],rows[1]) for rows in reader)
    

提交回复
热议问题