Add Attribute to Existing Object in Python Dictionary

27,109

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.

Share:
27,109
John Bartels
Author by

John Bartels

By Day: Senior Platform Engineer/DevOps Testing Manager By Night: I enjoy scripting, programming, engineering solutions, and testing applications. I have a rich background in networking and operations, but in the past few years, I have taken a greater liking to the development of applications and systems.

Updated on December 03, 2020

Comments

  • John Bartels
    John Bartels over 3 years

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