简体   繁体   English

使用 Dictreader 将 csv 文件读取为表格

[英]Reading csv file as a table with Dictreader

If I have a CSV file which is organized as below:如果我有一个 CSV 文件,其组织如下:

在此处输入图像描述

I am trying to use Dictreader for csv module:我正在尝试将 Dictreader 用于 csv 模块:

file =  open('file.csv')
csv_file = csv.DictReader(file)
data = {row['model']: row for row in csv_file}

I am trying to read this as a dictionary in which there is a separate dictionary for each model and its coefficients like this:我试图将此作为字典阅读,其中每个 model 及其系数都有一个单独的字典,如下所示:

{
  first:{a:1,b:2,c:3,d:4},
  second:{a:1,b:2,c:3,d:4},
  third:{a:1,b:2,c:3,d:4},
}

But I still have model name in the inner dictionary.但是我在内部字典中仍然有 model 名称。 How can I remove that?我怎样才能删除它?

You can pop the model key from each row dict instead:您可以从每一row字典中弹出model键:

data = {row.pop('model'): row for row in csv_file}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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