Python dictionary error AttributeError: 'list' object has no 'keys' attributes

I have an error with this line. I work with a dictionary from an import file. This is a dictionary:

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

And the method the following works with:

 def addData(dict, entry): new = {} x = 0 for i in dict.keys(): new[i] = entry(x) x += 1 dict.append(new) 

Where "dict" will be "users", but the error is that the dictionary does not recognize me as such. Can someone tell me if I have a wrong translation in the dictionary?

+6
source share
2 answers

Perhaps you are looking for something like that:

 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 turns the list of anonymous dicts into dict dicts, which are the keys for the 'id' key

+6
source

This is not a savage, this is a list of dictionaries!

EDIT: And to make this a bit more of an answer:

 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'}} 

This is essentially the same as dawgs, but with a simplified approach to creating a new dictionary

+6
source

All Articles