csv.dictreader没有提供所需的输出

时间:2012-12-25 05:02:06

标签: python

圣诞快乐!

我有以下数据:

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

1 个答案:

答案 0 :(得分: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