简体   繁体   English

如何在 python 中准确获取字典第一行的元素

[英]how to get exactly element of 1st row of dictionary in python

name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5

I did this:我这样做了:

with open(sys.argv[1], "r") as csvfile:使用 open(sys.argv[1], "r") 作为 csvfile:

reader = csv.DictReader(csvfile)
for row in reader:
    print(','.join(row))

and it printed:它打印:

name,AGATC,AATG,TATC名称,AGATC,AATG,TATC

name,AGATC,AATG,TATC名称,AGATC,AATG,TATC

name,AGATC,AATG,TATC名称,AGATC,AATG,TATC

I need to get access to AGATC AATG TATC i mean i have job to do with seperetly AGATC, AATG, TATC我需要访问 AGATC AATG TATC 我的意思是我有工作要单独处理 AGATC、AATG、TATC


sorry this is my first question here so i little confused what is what thank you for answer抱歉,这是我在这里的第一个问题,所以我有点困惑什么是什么谢谢你的回答

You can convert this reader object to list.您可以将此阅读器 object 转换为列表。 See into the below code看下面的代码

import csv

with open("sample.csv", "r") as csvfile: 
    reader = csv.DictReader(csvfile)
    print(list(reader))

Assuming that your OP is the contents of csv file, you just need:假设你的 OP 是 csv 文件的内容,你只需要:

reader.fieldnames

or maybe或者可能

reader.fieldnames[1:]

To be specific, you are looking for the first row in the csv file, which is usually the header row.具体来说,您正在查找 csv 文件中的第一行,通常是 header 行。 When you access the data rows with the Dict reader, you will get the data, with the keys provided by the header row.当您使用 Dict 阅读器访问数据行时,您将使用 header 行提供的键获取数据。

for x in reader:
     print (x)

Will show you the rows of data, as OrderedDicts:将向您显示数据行,如 OrderedDicts:

OrderedDict([('name', 'Alice'), ('AGATC', '2'), ('AATG', '8'), ('TATC', '3')])
OrderedDict([('name', 'Bob'), ('AGATC', '4'), ('AATG', '1'), ('TATC', '5')])
OrderedDict([('name', 'Charlie'), ('AGATC', '3'), ('AATG', '2'), ('TATC', '5')])

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

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