昨天我問了這個問題,但我仍然堅持下去。我寫了一個函數,目前正確讀取文件,但有幾個問題。將csv文件轉換爲字典
我遇到的主要問題是我需要以某種方式跳過文件的第一行,我不確定是否將它作爲字典返回。這裏是其中的一個文件的一個例子:
"Artist","Title","Year","Total Height","Total Width","Media","Country"
"Pablo Picasso","Guernica","1937","349.0","776.0","oil paint","Spain"
"Vincent van Gogh","Cafe Terrace at Night","1888","81.0","65.5","oil paint","Netherlands"
"Leonardo da Vinci","Mona Lisa","1503","76.8","53.0","oil paint","France"
"Vincent van Gogh","Self-Portrait with Bandaged Ear","1889","51.0","45.0","oil paint","USA"
"Leonardo da Vinci","Portrait of Isabella d'Este","1499","63.0","46.0","chalk","France"
"Leonardo da Vinci","The Last Supper","1495","460.0","880.0","tempera","Italy"
我需要閱讀像上面的一個文件,並將其轉換成看起來像這樣一本字典:
sample_dict = {
"Pablo Picasso": [("Guernica", 1937, 349.0, 776.0, "oil paint", "Spain")],
"Leonardo da Vinci": [("Mona Lisa", 1503, 76.8, 53.0, "oil paint", "France"),
("Portrait of Isabella d'Este", 1499, 63.0, 46.0, "chalk", "France"),
("The Last Supper", 1495, 460.0, 880.0, "tempera", "Italy")],
"Vincent van Gogh": [("Cafe Terrace at Night", 1888, 81.0, 65.5, "oil paint", "Netherlands"),
("Self-Portrait with Bandaged Ear",1889, 51.0, 45.0, "oil paint", "USA")]
}
這裏就是我有這麼遠。我目前的代碼工作,但不會像上面的例子那樣將文件轉換成字典。感謝您的幫助
def convertLines(lines):
head = lines[0]
del lines[0]
infoDict = {}
for line in lines:
infoDict[line.split(",")[0]] = [tuple(line.split(",")[1:])]
return infoDict
def read_file(filename):
thefile = open(filename, "r")
lines = []
for i in thefile:
lines.append(i)
thefile.close()
mydict = convertLines(read_file(filename))
return lines
只想給我的代碼一對夫婦的小變化返回正確的結果,或者我需要以不同的方式處理這個?它確實顯示我的當前代碼讀取完整文件。感謝您的任何幫助
編輯:@Julien它正在工作(但不正確),直到我今天早上做了一些修改它現在給出了遞歸錯誤。
你會得到什麼結果,你不滿意?這是相關的信息,所以請分享! – Julien
我敢打賭,你只是覆蓋每個藝術家的結果,而不是追加到列表中...... – Julien
我當前的代碼實際上是遞歸錯誤,但基本上我還沒有能夠創建一個字典,其中的關鍵是藝術家名字和價值觀是他們的繪畫,所以對於上面的例子應該有3個鍵,即使名字可以在文件中重複並且值是他們的繪畫(1爲畢加索,3爲達芬奇,2爲梵高) – n00bprogrammer22