我试图将属性添加到字典中的预先存在的对象中:
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"
Run Code Online (Sandbox Code Playgroud)
我尝试了各种组合(包括setattr等),但运气不太好。
将项目添加到字典后,如何将其他键/值对添加到该项目(而不是将其他项目添加到字典)。