向Python字典中的现有对象添加属性

2024-04-27 10:55:45 发布

您现在位置: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等),运气不太好。

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


Tags: the对象key字典属性objectnotdict
1条回答
网友
1楼 · 发布于 2024-04-27 10:55:45

在我写这个问题的时候,我意识到了我的错误。

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

dictObj[key]["property2"] = "value2"

问题似乎是,我正在将键为“key1”的对象实例化为字符串,而不是字典。因此,我无法向字符串添加键。这是我在试图解决这个简单问题时遇到的许多问题之一。当我稍微改变代码时,也遇到了一些键错误。

相关问题 更多 >