2015-08-20 109 views
1

我從csv文件中取得多行字符串,並試圖將其轉換爲字典。我寫了下面的代碼片段,我想使用它,但不知道如何使用它。在Python中將多行字符串轉換爲字典

scsv = '''coupon, months_to_maturity, FACE_VALUE, 
       0.3758, 12, 100, 
       0.7287, 24, 100, 
       1.0894, 36, 100, 
       1.4019, 48, 100, 
       1.6542, 60, 100, 
       1.8512, 72, 100, 
       2.0034, 84, 100, 
       2.1213, 96, 100, 
       2.2141, 108, 100, 
       2.2891, 120, 100, 
       2.3516, 132, 100, 
       2.4058, 144, 100, 
       2.4543, 156, 100, 
       2.4994, 168, 100, 
       2.5423, 180, 100, 
       2.5841, 192, 100, 
       2.6253, 204, 100, 
       2.6664, 216, 100, 
       2.7076, 228, 100, 
       2.7491, 240, 100, 
       2.7908, 252, 100, 
       2.8328, 264, 100, 
       2.8751, 276, 100, 
       2.9175, 288, 100, 
       2.9601, 300, 100, 
       3.0026, 312, 100, 
       3.0451, 324, 100, 
       3.0875, 336, 100, 
       3.1296, 348, 100, 
       3.1714, 360, 100, 
      ''' 
f = StringIO(scsv) 
reader = csv.reader(f, delimiter=',') 
for row in reader: 
    #Dont know what should go here 

謝謝

+0

你可能想使用['csv.DictReader'](https://docs.python.org/3/ library/csv.html#csv.DictReader)而不是'csv.reader'。 – dsh

+0

@dsh雖然這會導致一個'DictReader'對象。你能展示如何實現這個? – user131983

+0

你想在你的字典中鍵入什麼?如果是列標題,請記住,字典是無序的。 – Alexander

回答

1

你可以這樣做:

import os 
import csv 
from StringIO import StringIO 

scsv = """coupon, months_to_maturity, FACE_VALUE, 
       0.3758, 12, 100, 
       0.7287, 24, 100, 
       1.0894, 36, 100, 
       1.4019, 48, 100, 
       1.6542, 60, 100, 
       1.8512, 72, 100, 
       2.0034, 84, 100, 
       2.1213, 96, 100, 
       2.2141, 108, 100, 
       2.2891, 120, 100, 
       2.3516, 132, 100, 
      """ 

scsv = scsv.replace(' ','') #remove white spaces 
scsv = scsv.replace(',' + os.linesep, os.linesep) #remove commas at the end of the lines 

f = StringIO(scsv) 
reader = csv.DictReader(f, delimiter=',') 
rows = [row for row in reader] 

print rows[0] 
# {'coupon': '0.3758', 'months_to_maturity': '12', 'FACE_VALUE': '100'} 
相關問題