通过dict解析来分离键和值

时间:2016-07-26 23:56:23

标签: python

我的代码可以查看一个充满tsv文件的文件夹,并将该文件的名称作为键,并将列标题作为dict中的值。

row1 =[]
listdict=[] 
for f in files: 
    with open(dir_path  +'/'+f, 'rU') as file: 
        reader = csv.reader(file) 
        row1 = next(reader) 
        dict = {f: row1} 
        listdict.append(dict)

尝试访问dict listdict['file_name.tsv']时,出现错误

*** TypeError: list indices must be integers, not str

使用整数listdict[0]时,我似乎无法单独访问值,因为它们全部聚集在一起作为1值。

{'file_name.tsv': ['header1\theader2\theader3\theader4']}

如何单独访问每个标头。我的目标是创建一个csv输出,列出文件名和所有相关标题。

3 个答案:

答案 0 :(得分:4)

如果需要有序的元素列表,则使用list

当您需要一组无序的键值对时,会使用dict

如果您想按文件名(例如listdict['file_name.tsv'])查询文件标题,则需要使用dict。此外,如果要查询文件中的单个文件头,则需要使用list来保留订单:

listdict={}
for f in files:
    with open(dir_path  +'/'+f, 'r') as file:
        reader = csv.reader(file, delimiter='\t')
        row1 = next(reader)  # stores first row of tsv file in a list
        listdict[f] = row1

listdict中的条目如下所示:

{'file_name.tsv': ['header1', 'header2', 'header3', 'header4']}

listdict['file_name.tsv']会给你['header1', 'header2', 'header3', 'header4']

listdict['file_name.tsv'][0]会为您提供值'header1'

答案 1 :(得分:0)

您已通过listdicts = []创建了一个列表。

改为创建词典:listdicts = {}

 listdict={}
 for f in files: 
     with open(dir_path  +'/'+f, 'r') as file: 
         reader = csv.reader(file) 
         listdict[f] = next(reader).split() # split will split the headers by `\t`

并使用listdict['file_name.tsv'][0]访问相应的第一个标头。

答案 2 :(得分:0)

你可能想要这个

filedict={}
for f in files: 
    with open(dir_path  +'/'+f, 'rU') as file: 
        reader = csv.reader(file) 
        row1 = next(reader) 
        filedict[f] = row1
相关问题