2012-12-25 84 views
1

聖誕快樂!csv.dictreader沒有給出想要的輸出

,我有以下數據:

a = (" 101, 151,  0,'T1',2,2,1, 1.71470E-1,-1.02880E-1,2,'NUCA GSU ',1, 1,0.3200, 2,0.3900, 3,0.1400, 4,0.1500", 
"1.10000E-3, 9.10000E-2, 1200.00", 
"21.6000, 21.600, 0.000, 1200.00, 1100.00, 1000.00, 1, 101,22.68000,20.52000, 1.05000, 0.95000, 25, 0, 0.00021, 0.00051", 
"500.000, 500.000") 

b = (('I','J','K','CKT','CW','CZ','CM','MAG1','MAG2','NMETR','NAME', 
      'STAT','O1','F1','O2','F2','O3','F3','O4','F4'), 
      ('R1-2','X1-2','SBASE1-2'), 
      ('WINDV1','NOMV1','ANG1','RATA1','RATB1','RATC1','COD1','CONT1', 
      'RMA1','RMI1','VMA1','VMI1','NTP1','TAB1','CR1','CX1'), 
      ('WINDV2','NOMV2')) 

我想形成一個字典如下:

{'I': 101, 'J': 151, ...... 'F4': 0.1500} 
{'R1-2': 1.10000E-3, ...... 'SBASE1-2': 1200.0} 
{'WINDV1': 21.60, ...... 'ÇX1': 0.00051} 
{'WINDV2': 500.0, 'NOMV2': 500.0} 

我想用csv.DicReader所以我嘗試下面的代碼:

for j in range(4): 
    c=list(csv.DictReader(a[j], fieldnames=b[j])) 
    print c 

我沒有得到所需的輸出。我究竟做錯了什麼?

我已經可以做這樣的:

for j in range(4): 
    c=dict(zip(b[j], (a[j].split(',')))) 
    print c 

回答

2

我認爲這是簡單又未csv.DictReader,你是不是讀CSV。

newListOfDict=[] 
for keyLine, valueLine in zip(b, a): #one and one line from a and b 
    #the string line in b splitted and stripped 
    splittedValues = map(lambda v: v.strip(), valueLine.split(",")) 
    #create the new dict with the result of zip : ((b1, a1),(b2, a2)...) 
    newDict = dict(zip(keyLine, splittedValues)) 
    newListOfDict.append(newDict) 
print newListOfDict