2016-02-29 91 views
4

我試圖填補CSV數據的默認字典,我得到一個關鍵的錯誤KeyError異常灌裝Defaultdict的Python

for i in range(0,1): 

    #https://docs.python.org/2/library/collections.html#collections.defaultdict 
    result = co.defaultdict(list) 
    with open(os.path.join(inputdir,tablelist[i])) as f: 

     csv_reader = csv.reader(f) 
     csv_headings = next(csv_reader) 
     read = csv.DictReader(f) 

     for line in read: 
      for j in range(1,len(csv_headings)): 
    error here--->result[line[csv_headings[0]]].append(line[csv_headings[j]]) 

爲CSV數據

API,CNTYNM,PRMT, 
4700100002,Barbour,2, 
4700100003,Barbour,3, 
4700100004,Barbour,4, 

關鍵的錯誤是API,它對我來說意味着與dictreader的東西不能按預期工作,任何人都可以提供一些建議?

回答

2

您缺少fieldnames的參數DictReader。如果您修改代碼以傳遞csv_haedingsDictReader它會工作(希望如預期):

for i in range(0,1): 

    #https://docs.python.org/2/library/collections.html#collections.defaultdict 
    result = co.defaultdict(list) 
    with open(os.path.join(inputdir,tablelist[i])) as f: 

     csv_reader = csv.reader(f) 
     csv_headings = next(csv_reader) 
     read = csv.DictReader(f, fieldnames=csv_headings) 

     for line in read: 
      for j in range(1,len(csv_headings)): 
       result[line[csv_headings[0]]].append(line[csv_headings[j]]) 
+0

哦,我沒有看到,大約一個半小時了。謝謝,我沒有意識到fieldnames必須傳遞給dictreader,但是它確實造成了snesne –