25

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

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

And the method with which the work is as follows:

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

Where "dict" would be "users", but the error is that the dictionary does not recognize me as such. Can anyone tell me, I have wrong in the dictionary?

2
  • 1
    Your users variable is actually a list of dictionaries. Commented Apr 21, 2014 at 2:53
  • I actually defined a variable as dict in a pyx file but after importing the generated. " pyd" file, I am getting the following error when getting its keys: AttributeError: 'getset_descriptor' object has no attribute 'keys' Commented Mar 9, 2020 at 12:54

2 Answers 2

14

That's not a dicionary, it's 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

Sign up to request clarification or add additional context in comments.

4 Comments

That's not an answer, it's a comment!
You're right, but without 50 reputation I can't comment (which I would have done). But it seems to me, that this hint might have helped anyway.
Sorry, didn't notice your rep. If you fleshed out some details, I'd upvote
Done. Although it's actually just an improvement to dawgs answer, so not really worth the upvote i guess.
12

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'

You can more compactly do this in one line:

new_dict={d['id']:{k: d[k] for k in d.keys() - {'id'}} for d in users} # {1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.