python - 将属性添加到 Python 字典中的现有对象

标签 python dictionary attributes

我试图向字典中预先存在的对象添加一个属性:

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/

相关文章:

Python - 检查字典中是否存在列表项

html - 如何将 Bootstrap 类应用于 css 文件中的每个相同 HTML 元素?

python - 如何获取文件夹中文件的序号?

python - WSGIDaemon 进程语法错误 - Mod_wsgi django ImportError : No module named django. core.wsgi

python - 如何从Python的行列表中选择特定元素

python - 将列表解包为字典中的键——Python 3.4

php - 通过相关性(模糊,同义词)进行 mySQL 搜索

javascript - 用工具提示的跨度替换标题属性对 SEO 来说是个坏主意吗?

c++ - 如何在 ns3 中使用属性

python - 无法使用Scrapy项作为MySQL.execute : "Wrong number of arguments during string formatting"的数据