2016-03-06 37 views
6

,我有以下格式的csv文件,蟒蛇讀取CSV文件,行和列標題到字典中有兩個鍵

,col1,col2,col3 
row1,23,42,77 
row2,25,39,87 
row3,48,67,53 
row4,14,48,66 

我需要讀入兩個鍵的字典這使得

dict1['row1']['col2'] = 42 
dict1['row4']['col3'] = 66 

如果我嘗試使用csv.DictReader使用默認選項

with open(filePath, "rb") as theFile: 
    reader = csv.DictReader(theFile, delimiter=',') 
    for line in reader: 
    print line 

我得到以下輸出

{'': 'row1', 'col2': '42', 'col3': '77', 'col1': '23'} 
{'': 'row2', 'col2': '39', 'col3': '87', 'col1': '25'} 
{'': 'row3', 'col2': '67', 'col3': '53', 'col1': '48'} 
{'': 'row4', 'col2': '48', 'col3': '66', 'col1': '14'} 

我不知道如何處理此輸出,以便創建我感興趣的字典的類型。

爲了完整起見,也將有助於如果你能解決如何用上述格式將字典寫回csv文件

回答

10

使用CSV模塊:

import csv 
dict1 = {} 

with open("test.csv", "rb") as infile: 
    reader = csv.reader(infile) 
    headers = next(reader)[1:] 
    for row in reader: 
     dict1[row[0]] = {key: int(value) for key, value in zip(headers, row[1:])} 
+0

這工作,看起來優雅 – WanderingMind

+1

我有一個問題,字典中的值是字符串,而不是整數。如何確保字典中的值是整數 – WanderingMind

+1

請參閱我的編輯 - 只需在每個值上調用int();但是,即使單個值不能轉換爲整數,這也會失敗。 –

1

輸入文件的格式與csv模塊解析不太方便。我會分開解析標題,然後逐行解析其餘行,分割,,剝離並製作字典。工作代碼:

from pprint import pprint 

d = {} 
with open("myfile.csv") as f: 
    headers = [header.strip() for header in next(f).split(",")[1:]] 

    for line in f: 
     values = [value.strip() for value in line.split(",")] 
     d[values[0]] = dict(zip(headers, values[1:])) 

pprint(d) 

打印:

{'row1': {'col1': '23', 'col2': '42', 'col3': '77'}, 
'row2': {'col1': '25', 'col2': '39', 'col3': '87'}, 
'row3': {'col1': '48', 'col2': '67', 'col3': '53'}, 
'row4': {'col1': '14', 'col2': '48', 'col3': '66'}} 
4

您可以使用pandas的,即使這是一個有點矯枉過正。親是,幾乎沒有什麼可以編碼來獲得預期的結果。

# Reading the file 
df = pd.read_csv('tmp.csv', index_col=0) 

# Creating the dict 
d = df.transpose().to_dict(orient='series') 

print(d['row1']['col2']) 
42 
+0

這個答案是優雅。不幸的是,我正在Pandas不在的服務器上工作。我不希望修改任何python設置,因爲它可能會打破其他感興趣的包。 – WanderingMind