2015-12-02 70 views
0

我試圖將一個屬性在字典添加到預先存在的對象:添加屬性到現有的對象在Python字典

key = 'key1' 
dictObj = {} 
dictObj[key] = "hello world!" 

#attempt 236 (j/k) 
dictObj[key]["property2"] = "value2" ###'str' object does not support item assignment 

#another attempt 
setattr(dictObj[key], 'property2', 'value2') ###'dict' object has no attribute 'property2' 

#successful attempt that I did not like 
dictObj[key] = {'property':'value', 'property2':''} ###instantiating the dict object with all properties defined seemed wrong... 
#this did allow for the following to work 
dictObj[key]["property2"] = "value2" 

我嘗試各種組合(包括SETATTR等)並且沒有具有祝你好運。

一旦我將一個項目添加到詞典中,我怎樣才能將其他鍵/值對添加到該項目中(而不是將其他項目添加到詞典中)。

回答

1

當我寫這個問題時,我意識到我的錯誤。

key = 'key1' 
dictObj = {} 
dictObj[key] = {} #here is where the mistake was 

dictObj[key]["property2"] = "value2" 

這個問題似乎是我實例化對象與鍵「鍵1」作爲一個字符串,而不是一本字典。因此,我無法將密鑰添加到字符串中。這是我在試圖找出這個簡單問題時遇到的許多問題之一。當我改變代碼時,我遇到了KeyErrors。

相關問題