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



只能使用CSV作为高级模块,如何将以下数据转换为字典?第一行(标题(必须是字典的关键字。到目前为止,我只找到了读取第一列作为关键字的方法。

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文件,其中的头行是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:]]

最新更新