2016-07-26 99 views
0

我有一個代碼,通過一個文件夾來查看完整的tsv文件,並抓取文件的名稱作爲鍵和列標題作爲字典中的值。解析字典來分離鍵和值

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) 

試圖訪問該字典listdict['file_name.tsv']的時候,我得到一個錯誤

使用int listdict[0]
*** TypeError: list indices must be integers, not str 

,我似乎不能分別訪問值作爲他們都聚集在一起爲1倍的值。

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

如何分別訪問每個標頭。我的目標是創建一個csv輸出,列出文件名和所有相關的標題。

+1

看來你已經通過'append'在你的代碼中糾正了你的錯誤。此外,'listdict'是一個列表,而不是字典。另外,你最好使用不是類型的變量名(命名變量'list'或'dict'或'file'是一個可怕的想法) – inspectorG4dget

回答

4

一個list使用。

A 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

你也可以使用[OrderedDict](https:// docs .python.org/2/library/collections.html#collections.OrderedDict)來保存字典中項目的順序:) –

+0

我得到一個'AttributeError:'列表'對象沒有屬性'split''錯誤信息。我的輸出實際上是'{'filename.tsv':['header1 \ theader2 \ theader3 \ theader4']}''與\ t中間標題。我也做了上面的編輯。 – nlr25

+0

對不起,應該由讀者自動分開。編輯答案,現在應該是好的。 – victor

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]訪問相應的第一個標題。

0

你可能想,當你想要一個有序的元素列表此

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