python如何迭代CSV文件中同一列中的单元格?

2024-06-24 12:45:13 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个包含以下列的csv文件:

system     component    version  otherColumn...

type1         abc          4      
              qwe          5
              asd          6

type2         rty          3

type3         vbn          8
              asd          9

我想将CSV文件解析为字典,如下所示:

{
 type1: { abc: 4, qwe: 5,asd: 6}
 type2: { rty: 3}
 type3: { vbn: 8, asd: 9}
}

我只想要上面的三列,其他的不需要。你知道吗

我试了以下方法:

import csv

dict = {}
f = open("myfile", 'rt')
reader = csv.reader(f)
     for col in row
        if col == 'system':
            //I am stuck here

有人能帮忙吗?你知道吗

提前谢谢。你知道吗


Tags: 文件csvversioncolsystemreadercomponentabc
1条回答
网友
1楼 · 发布于 2024-06-24 12:45:13

此处:

import csv

data = {}
with open("myfile", "rb") as f:
    reader = csv.DictReader(f)
    for row in reader:
        d = data.setdefault(row["system"], {})
        # Here, you may want to handle invalid values in the version field
        d[row["component"]] = int(row["version"])

相关问题 更多 >