Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python add dictionary to existing dictionary

Tags:

python

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'

like image 842
user391986 Avatar asked Dec 02 '22 00:12

user391986


2 Answers

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.

like image 152
Adam Wagner Avatar answered Dec 24 '22 11:12

Adam Wagner


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

topid["subid"].append(insubid)

to:

topid["subid"] = insubid
like image 31
ewegesin Avatar answered Dec 24 '22 10:12

ewegesin