我试图向字典中预先存在的对象添加一个属性:
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 等),但运气不佳。
将项目添加到字典后,如何向该项目添加其他键/值对(而不是向字典添加其他项目)。
最佳答案
当我写这个问题时,我意识到我的错误。
key = 'key1'
dictObj = {}
dictObj[key] = {} #here is where the mistake was
dictObj[key]["property2"] = "value2"
问题似乎是我将带有键“key1”的对象实例化为字符串而不是字典。因此,我无法将键添加到字符串。这是我在尝试解决这个简单问题时遇到的众多问题之一。当我稍微改变代码时,我也遇到了 KeyErrors。
关于python - 将属性添加到 Python 字典中的现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046609/