簡體   English   中英

如何在不使用任何高級模塊代替 csv 的情況下將 csv 文件讀入字典

[英]How to read csv file into dictionary without using any advanced module instead of 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}

這是我預期的 output:

[{'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:]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM