python字典错误AttributeError:'list'对象没有属性'keys'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23190074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:27:19  来源:igfitidea点击:

python dictionary error AttributeError: 'list' object has no attribute 'keys'

pythondictionary

提问by Ginko

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?

其中“dict”将是“users”,但错误是字典无法识别我。谁能告诉我,我的字典有错?

采纳答案by dawg

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'

从本质上讲,这是将匿名字典列表转换为来自密钥的密钥的字典 'id'

回答by Daniel

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

这与 dawgs 的答案基本相同,但使用简化的方法生成新字典