簡體   English   中英

需要獲取 csv 文件中的每一行並存儲在字典中

[英]need to fetch each row in csv file and store in a dictionary

大家好,我有一個 csv 文件,我需要在其中迭代 csv 的每一行,然后將其存儲在帶有鍵和值的字典中,

密鑰將是 CSV 的 header

例如,我有一個 CSV 名稱為 csv_file_data:

    sno.    val-1   val-2
      1       200      20
      2        22      44
      3        56      32
      4        32      45

形成這個我需要以下output:

    {'csv_file_data':[{'val-1':200,'val-2':20},{'val-1':22,'val-2':44},{'val-1':56,'val-2':32},{'val-1':32,'val-2':45}]}

嗨,兄弟,

 data_dict=[{'csvfile1_data': [{'val-1': '0', 'val-2': '0'}, {'val-1': '0', 'val-2': '0'}]}, {'csvfile2_data': [{'val-3': '138', 'val-4': '0'}, {'val-3': '0', 'val-4': '0'}]}]

 input=('input_file' [{'val-1': '100', 'val-4': '1990'}, {'val-2': '90', 'val-1': '0.0'}])

所以在這里,我需要用第一個列表替換 input_file 中的值

output 我需要:

 data_dict=[{'csvfile1_data': [{'val-1': '100', 'val-2': '0'}, {'val-1': '0', 'val-2': '90'}]}, {'csvfile2_data': [{'val-3': '138', 'val-4': '1990'}, {'val-3': '0', 'val-4': '0'}]}]
def get_data_csv(fn):

    mylist = []
    
    with open(fn, "r") as msg:
        for line in msg:
            mylist.append(line.strip())
        msg.close()
    
    mydict = {}
    mydict['csv_file_data'] = []
    
    headers = mylist[0].split()
    
    del mylist[0]
    
    for line in mylist:
        tmp_dict = {}
        tmp_dict[headers[1]] = int(line.split()[1])
        tmp_dict[headers[2]] = int(line.split()[2])
        mydict['csv_file_data'].append(tmp_dict)
    
    return mydict

您將數據加載到mylist.

你用一個空列表聲明你的字典和mydict['csv_file_data']

然后你從mylist[0].split()得到你的標題。

由於您不需要mylist[0] ,因此您可以刪除它。

您閱讀mylist中的其他行,將它們拆分並將它們加載到具有相關鍵(標題)的臨時字典中。

然后你 append 那tmp_dictmydict

你得到:

{'csv_file_data': [{'val-1': 200, 'val-2': 20}, {'val-1': 22, 'val-2': 44}, {'val-1': 56, 'val-2': 32}, {'val-1': 32, 'val-2': 45}]}

暫無
暫無

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

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