user391986
user391986

Reputation: 30956

python add dictionary to existing dictionary

What am I doing wrong here? The append inside the dictionary doesn't seem to be working

final = []

topid = { 
    "ida" : "ida",
    "idb" : "idb",
    "idc" : "idc",
    "subid" : {}
}

for subid in subids:
    insubid = {
        "name" : subid.name, 
        "sida" : "sida",
        "sidb" : "sidb",
        "sidc" : "sidc",
    }
    topid["subid"].append(insubid)

final.append(topid)

I'm getting the error:

AttributeError: 'dict' object has no attribute 'append'

Upvotes: 4

Views: 23908

Answers (2)

ewegesin
ewegesin

Reputation: 329

If I'm understanding this correctly, all you need to do is change:

topid["subid"].append(insubid)

to:

topid["subid"] = insubid

Upvotes: 7

Adam Wagner
Adam Wagner

Reputation: 16117

I'm not sure this is what you want, but by using append, your code is expecting subid to be a list. If that's what you are going for, you should be able to change this:

topid = { 
    "ida" : "ida",
    "idb" : "idb",
    "idc" : "idc",
    "subid" : {}
}

to this:

topid = { 
    "ida" : "ida",
    "idb" : "idb",
    "idc" : "idc",
    "subid" : []
}

Notice that subid is now an empty list, instead of a dictionary.

Upvotes: 11

Related Questions