python dictionary error AttributeError: list object has no attribute keys

python dictionary error AttributeError: list object has no attribute keys

Thats not a dicionary, its a list of dictionaries!
EDIT: And to make this a little more answer-ish:

users = [{id:1010,name:Administrator,type:1},{id:1011,name:Administrator2,type:1}]
newusers = dict()
for ud in users:
    newusers[ud.pop(id)] = ud
print newusers
#{1010: {type: 1, name: Administrator}, 1011: {type: 1, name: Administrator2}}
newusers[1012] = {name: John, type: 2}
print newusers
#{1010: {type: 1, name: Administrator}, 1011: {type: 1, name: Administrator2}, 1012: {type: 2, name: John}}

Which is essentially the same as dawgs answer, but with a simplified approach on generating the new dictionary

Perhaps you are looking to do something along these lines:

users = [{id:1010,name:Administrator,type:1},{id:1011,name:Administrator2,type:1}]

new_dict={}

for di in users:
    new_dict[di[id]]={}
    for k in di.keys():
        if k ==id: continue
        new_dict[di[id]][k]=di[k]

print new_dict     
# {1010: {type: 1, name: Administrator}, 1011: {type: 1, name: Administrator2}} 

Then you can do:

>>> new_dict[1010] 
{type: 1, name: Administrator}

Essentially, this is turning a list of anonymous dicts into a dict of dicts that are keys from the key id

python dictionary error AttributeError: list object has no attribute keys

Leave a Reply

Your email address will not be published.