将属性添加到Python词典中的现有对象

Joh*_*els 4 python attributes dictionary

我试图将属性添加到字典中的预先存在的对象中:

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等),但运气不太好。

将项目添加到字典后,如何将其他键/值对添加到该项目(而不是将其他项目添加到字典)。

Joh*_*els 11

当我写这个问题时,我意识到自己的错误。

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

dictObj[key]["property2"] = "value2"
Run Code Online (Sandbox Code Playgroud)

问题似乎是我使用键“ key1”作为字符串而不是字典实例化该对象。因此,我无法在字符串中添加键。这是我试图弄清楚这个简单问题时遇到的许多问题之一。当我稍微改变代码时,我也遇到了KeyErrors。