17

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).

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.