Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Attribute to Existing Object in Python Dictionary

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

like image 546
John Bartels Avatar asked Dec 02 '15 15:12

John Bartels


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

like image 188
John Bartels Avatar answered Sep 19 '22 21:09

John Bartels