我试图将一个属性添加到字典中的预先存在的对象中:
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等)并没有太多运气。
将项目添加到词典后,如何向该项目添加其他键/值对(不将其他项目添加到词典中)。
答案 0 :(得分:5)
当我写这个问题时,我发现了自己的错误。
key = 'key1'
dictObj = {}
dictObj[key] = {} #here is where the mistake was
dictObj[key]["property2"] = "value2"
问题似乎是我用键'key1'作为字符串而不是字典来实例化对象。因此,我无法在字符串中添加密钥。这是我在试图找出这个简单问题时遇到的众多问题之一。当我改变代码时,我也遇到了KeyErrors。