2016-10-14 155 views
0

請,我需要讀取CSV文件並將結果轉換爲字典。將cvs文件讀取到字典python

文件輸入:

enter image description here

閱讀像下面後所需的對象:

defaultdict(<type 'dict'>, {‘Book’: {‘Book’: 1.0, ‘Afnan’: 0, ‘Location’: 0, ‘Love’: 0}, ‘Afnan’: {‘Book’: 0, ‘Afnan’: 1.0, ‘Location’: 0.71, ‘Love’: 0}, ‘Location’: {‘Book’: 0, 'Afnan’: 0.71, ‘Location’: 1.0, ‘Love’: 0}, ‘Love’: {‘Book’: 0, ‘Afnan’: 0, ‘Location’: 0, ‘Love’: 1.0}}) 

我下面寫代碼,但不工作,因爲我想要的東西。請幫忙。

reader = unicode_csv_reader(open('cos3.csv')) 
x=list(reader) 
for i in x: 
    if isinstance(i,float): 
     arr=np.array(x).astype('float') 
    else: 
     arr=np.array(x).astype('string') 
d=defaultdict(dict) 
for a in arr: 
    for b in arr: 
     d[a][b]=arr(a) 
+0

電子表格的圖像**不是** csv文件的正確表示。它不顯示分隔符和最終引號,相反,它可以讓我們認爲表單的名稱(這裏是表1)在文件中。下一次,請顯示文本編輯器(記事本,vi等)將顯示的內容。 –

回答

0

我總是用csv.DictReader然後生成字典你想要像這樣的格式:

enter image description here

import csv 
import os 
cwd = os.getcwd() 


d_out = {} 
with open(cwd+'\\example.csv', 'rb') as file_in: 
    reader = csv.DictReader(file_in, restkey=None, restval=None, dialect='excel') 
    for row in reader: 
     d_out.setdefault(row['Key'], {'Book':row['Book'], 'Afnan':row['Afnan'], 'Location':row['Location'], 'Love':row['Love']}) 


print d_out 

希望這有助於!