我想將我的csv.reader中的東西轉換爲字典。我執行了這個帖子Add new keys to a dictionary?的指示,但我一直得到IndexError: list index out of range
。我怎樣才能解決這個問題?向字典中添加新元素
import wx
import csv
info = csv.reader(open('report.csv', 'rb'),delimiter=',')
length = 0
info_list = []
for row in info: #search each row in the report
info_list.append([length,row[1],row[4]])
length = length + 1
print length
dict_info = {}
rows = 0
counter = 0
while counter < length:
for item in info_list:
dict_info[item[rows]] = [item[rows + 1], item[rows + 2]]
rows = rows + 3
counter = counter + 1
print dict_info
你能解釋一下你想在段落中實現什麼嗎? –
您正在遍歷您迭代的第二個'item'的邊界,這是一個列表,因爲'while'循環的每次迭代都會將您正在索引到'item'的'row'值加3,但是' item'只有3個元素長(因爲你在循環'info'的時候創建了它)。列表中出現索引錯誤;字典沒有問題。我第二@JonClements雖然想知道你實際上想要做什麼。 –