【问题标题】:need to fetch each row in csv file and store in a dictionary需要获取 csv 文件中的每一行并存储在字典中
【发布时间】:2021-03-12 03:20:25
【问题描述】:

大家好,我有一个 csv 文件,我需要在其中迭代 csv 的每一行,然后将键和值存储在字典中,

密钥将是 CSV 的标题

例如,我有一个 CSV 名称为 csv_file_data:

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

形成这个我需要以下输出:

    {'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 中存在的值替换为第一个列表

我需要的输出:

 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'}]}]

【问题讨论】:

  • 你的输出是一个列表类型,因为你设置了 output = [] 这意味着你有一个空列表。
  • 为什么不直接使用csv.DictReader
  • @Module_art oohh ok 所以我需要该列表作为值和 csv_file_data 作为键
  • @buran 我不知道如何使用 csv.DictReader,但谢谢我会检查这个
  • return {'csv_file_data':list_values} ?

标签: python list csv dictionary tuples


【解决方案1】:
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]你del就可以了。

您阅读mylist 中的其他行,将它们拆分并加载到具有相关键(标题)的临时字典中。

然后将 tmp_dict 附加到 mydict

你会得到:

{'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}]}

【讨论】:

  • 谢谢,但我在这个 tmp_dict[headers[1]] = line.split()[1] IndexError: list index out of range 中遇到错误
  • 好吧,我在我的文本编辑器中复制/粘贴了您的数据并在上面制作了它。没问题。您的数据与您发布的数据完全相同吗?你的文本编辑器是什么?您是否像示例中那样用空格分隔?
  • 我使用的是pycharma,而且csv数据也不同而且很大,这样我就举了一个csv的例子
  • 好吧,如果您的 csv 具有给定数量的行和列,并且没有丢失任何值,那么它必须工作。尝试使用 .split(",") 或 .split("\t") 以防您的 csv 由逗号或制表符而不是您的示例中的空格分隔。
  • 我还有一个问题,你能帮我吗:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多