【问题标题】:Reading csv file as a table with Dictreader使用 Dictreader 将 csv 文件作为表格读取
【发布时间】:2020-04-14 19:10:11
【问题描述】:

如果我有一个按如下方式组织的 CSV 文件:

我正在尝试将 Dictreader 用于 csv 模块:

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

我试图将其视为字典,其中每个模型都有一个单独的字典,其系数如下:

{
  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},
}

但我仍然在内部字典中有型号名称。我怎样才能删除它?

【问题讨论】:

  • 当你说你想要“模型名称......删除[d]”时,你是说你想要输出作为一个列表,只包含值吗?像这样:"first" : [1,2,3,4],
  • 可以,这个输出也可以接受

标签: python csv dictionary


【解决方案1】:

您可以改为从每个 row 字典中弹出 model 键:

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

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多