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等)並且沒有具有祝你好運。
一旦我將一個項目添加到詞典中,我怎樣才能將其他鍵/值對添加到該項目中(而不是將其他項目添加到詞典中)。