2012-04-09 59 views
0

我想在Python中爲CSV文件添加一個新的鍵:值。密鑰的新值來自表中現有密鑰的值。Python添加到詞典.csv格式

def addKey(allData): 
    allData = [] 
    for i in range (0, len(allData)): 
     while i > 0 and allData[i] == allData[i+1]: 
      newKey = {} 
      newKeyVal = int(allData['key1']*100 + allData['key2']) 
      allData = dict(allData, newKey = newKeyVal) 
    return allData 

有什麼建議嗎?我有一種感覺,這個代碼從一開始就是錯誤的。

回答

0

如果allData已經是一個字典,那麼你會希望

allData["newkey"] = newKeyVal 

IIRC,http://stardict.sourceforge.net/Dictionaries.php下載只會讓你的每個關鍵之一,所以只要「則newkey」並不在字典中已經存在它只會添加它。

你可能不希望

allData = [] 
在那裏

無論是。

+0

謝謝,到目前爲止我做了這些更改,但是,現在我得到「IndexError:list index out of range」for this line:while i> 0 and allData [i] == allData [i + 1] : – user1322596 2012-04-09 20:17:44