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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With