繁体   English   中英

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

[英]python how to iterate cells in the same column in a CSV file?

假设我有一个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}
}

我只想要字典中的上述3列。 其他列不是必需的。

我尝试如下:

import csv

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

有人可以帮忙吗?

提前致谢。

这里:

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"])

暂无
暂无

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

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