[英]How to read csv file into dictionary without using any advanced module instead of csv
Can only use CSV as advanced modules, how do I convert the following data into a dictionary?只能用CSV作为高级模块,下面的数据怎么转换成字典? The first row(header) has to be the key for the dictionary.
第一行(标题)必须是字典的键。 So far I only found the method to read the first column as the key.
到目前为止,我只找到了读取第一列作为键的方法。
DB,Field1,Field2,Field3
A,DataF1,DataF2,DataF3
B,MoreDataF1,MoreDataF2,MoreDataF3
C,SomeMoreDataF1,SomeMoreDataF2,SomeMoreDataF3
This is my work did currently:这是我目前所做的工作:
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}
This is my expected output:这是我预期的 output:
[{'DB': 'A',
'Field1': 'DataF1',
'Field2': 'DataF2',
'Field3': 'DataF3'},
{'DB': 'B',
'Field1': 'MoreDataF1',
'Field2': 'MoreDataF2',
'Field3': 'MoreDataF3'}]
You can read a csv file by opening it through the conventional way: open()
.您可以通过常规方式打开 csv 文件来读取它:
open()
。 Then, create a list with lines.然后,创建一个包含线条的列表。 Then,
split(',')
each line.然后,
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]
Now you have a table
which traduces your csv file, in which the header row is table[0]
.现在你有一个
table
,它会引用你的 csv 文件,其中 header 行是table[0]
。 You can now handle the data contained in the csv file, and convert it into a list of dictionaries:您现在可以处理 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)
That is it.这就对了。 Of course, you can compress it all into few lines through list and dictionary comprehension:
当然,你可以通过列表和字典理解将它全部压缩成几行:
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:]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.