简体   繁体   中英

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? 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:

[{'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() . Then, create a list with lines. Then, split(',') each line.

#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] . You can now handle the data contained in the csv file, and convert it into a list of dictionaries:

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:]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM