繁体   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