2012-05-10 38 views
0

我想創建一個基於csv第1列作爲關鍵字的字典。我可以使用.split()來做到這一點,或將csv.dictreader自動從第一列的基礎鑰匙?可以使用.split()和csv.reader嗎?

from collections import defaultdict 
import csv 
import sys 

#import csv file and store in dictionary 
dict=defaultdict(list) 
file=csv.reader(open(‘sys.argv[1]’,‘rt’)) 
    for f in file: 
     a,b,c,d=f.split() 
     dict[a].append((b,c,d)) 
file.close() 
+0

如果「列」你的意思是「行」,那麼dictreader已經可以做到這一點 –

回答

3

csv.reader應該已經根據您指定的分隔符分割您的行。因此,像這樣:

csv_file = csv.reader(open(filename, "rb"), delimiter=",") 
for row in csv_file: 
    print row 

會給你這樣的:

["an element", "another element", "a third element"] 
["an element", "another element", "a third element"] 
["an element", "another element", "a third element"] 
    .... 

你不應該這樣做row.split()

一對夫婦更多的事情:

1)不要覆蓋蟒蛇內置的名字。 file是python builtin(如是dict)。打電話給你的讀者csv_file或其他東西(並重新命名你的字典)。

2)除非你打算在你的腳本中使用defaultdict能力後,你需要的是一個很好的舊規則dict

3)沒有必要擺在首位,以解開的f內容的兩倍。你讓成兩個步驟這個時候只需要一個:

實施

myDict = {} 
for row in csv_file: 
    myDict[row[0]] = row[1:] 
相關問題