Creating a dictionary from a csv file?

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

    Many solutions have been posted and I'd like to contribute with mine, which works for a different number of columns in the CSV file. It creates a dictionary with one key per column, and the value for each key is a list with the elements in such column.

        input_file = csv.DictReader(open(path_to_csv_file))
        csv_dict = {elem: [] for elem in input_file.fieldnames}
        for row in input_file:
            for key in csv_dict.keys():
                csv_dict[key].append(row[key])
    

提交回复
热议问题