Add Attribute to Existing Object in Python Dictionary

Question:

I was attempting to add an attribute to a pre-existing object in a 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"

I tried various combinations (including setattr, etc.) and was not having much luck.

Once I have added an item to a Dictionary, how can I add additional key/value pairs to that item (not add another item to the dictionary).

Asked By: John Bartels

||

Answers:

As I was writing up this question, I realized my mistake.

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

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

The problem appears to be that I was instantiating the object with key ‘key1’ as a string instead of a dictionary. As such, I was not able to add a key to a string. This was one of many issues I encountered while trying to figure out this simple problem. I encountered KeyErrors as well when I varied the code a bit.

Answered By: John Bartels

Strictly reading the question, we are considering adding an attribute to the object. This can look like this:

class DictObj(dict):
  pass

dictObj = DictObj(dict)

dictObj.key = {'property2': 'value2'}

And then, we can use dictObj.key == {'property2': 'value2'}

Given the context of the question, we are dealing with adding a property to the dictionary. This can be done (in addition to @John Bartels’s approach) in the following ways:

1st option – add the "full" content in one line:

dictObj = {'key': {'property2': 'value2'}}

2nd option for the case of dictionary creation with initial values:

dictObj = dict(key = dict(property2 = 'value2'))

3rd option (Python 3.5 and higher):

dictObj  = {}
dictObj2 = {'key': {'property2': 'value2'}}
dictObj  = {**dictObj, **dictObj2}

4th option (Python 3.9 and higher):

dictObj = {}
dictObj |= {'key': {'property2': 'value2'}}

In all cases the result will be: dictObj == {'key': {'property2': 'value2'}}

Answered By: Roman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.