python dictionary error AttributeError: list object has no attribute keys

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!
nEDIT: And to make this a little more answer-ish:

n

users = [{id:1010,name:Administrator,type:1},{id:1011,name:Administrator2,type:1}]nnewusers = dict()nfor ud in users:n    newusers[ud.pop(id)] = udnprint newusersn#{1010: {type: 1, name: Administrator}, 1011: {type: 1, name: Administrator2}}nnewusers[1012] = {name: John, type: 2}nprint newusersn#{1010: {type: 1, name: Administrator}, 1011: {type: 1, name: Administrator2}, 1012: {type: 2, name: John}}n

n

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:

n

users = [{id:1010,name:Administrator,type:1},{id:1011,name:Administrator2,type:1}]nnnew_dict={}nnfor di in users:n    new_dict[di[id]]={}n    for k in di.keys():n        if k ==id: continuen        new_dict[di[id]][k]=di[k]nnprint new_dict     n# {1010: {type: 1, name: Administrator}, 1011: {type: 1, name: Administrator2}} n

n

Then you can do:

n

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

n

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

Related posts on python :

Leave a Reply

Your email address will not be published.