如何在不使用任何高级模块而不是 csv 的情况下将 csv 文件读入字典

How to read csv file into dictionary without using any advanced module instead of csv

高级模块只能用CSV,请问下面的数据怎么转换成字典?第一行(header)必须是字典的键。目前只找到读取第一列为key的方法

DB,Field1,Field2,Field3
A,DataF1,DataF2,DataF3
B,MoreDataF1,MoreDataF2,MoreDataF3
C,SomeMoreDataF1,SomeMoreDataF2,SomeMoreDataF3

这是我目前所做的工作:

import csv
dict_from_csv = {}
    with open('library-titles.csv', mode='r') as inp:
    reader = csv.reader(inp)
    dict_from_csv = {rows[0]:rows[1] for rows in reader}

这是我的预期输出:

[{'DB': 'A',
 'Field1': 'DataF1',
 'Field2': 'DataF2',
 'Field3': 'DataF3'},

 {'DB': 'B',
 'Field1': 'MoreDataF1',
 'Field2': 'MoreDataF2',
 'Field3': 'MoreDataF3'}]

您可以通过常规方式打开csv文件进行读取:open()。然后,创建一个包含线条的列表。然后,split(',') 每行。

#first load the file
csv_file = open(file_path, 'r')

#then collect the lines
file_lines = csv_file.readlines()

#remove the '\n' at the end of each line
file_lines = [line[:-1] for line in file_lines]

#collect the comma separated values into lists
table = [line.split(',') for line in file_lines]

现在您有一个 table,它会翻译您的 csv 文件,其中 header 行是 table[0]。您现在可以处理包含在 csv 文件中的数据,并将其转换为字典列表:

dict_list = []
for line in table[1:]: #exclude the header line
    dict_from_csv = {}
    for i, elem in enumerate(line):
        dict_from_csv[table[0][i]] = elem #for each line elem, associate it to its header relative
    dict_list.append(dict_from_csv)

就是这样。当然,你可以通过列表和字典理解把它全部压缩成几行:

with open(filepath,'r') as csv_file:
    table = [strline[:-1].split(',') for strline in csv_file.readlines()]
    dict_list = [{table[0][i]:elem for i, elem in enumerate(line)} for line in table[1:]]