Python 为什么我得到“列表”对象没有属性“项目”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33949856/
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
Why I get 'list' object has no attribute 'items'?
提问by Jand
Using Python 2.7, I have this list:
使用 Python 2.7,我有这个列表:
qs = [{u'a': 15L, u'b': 9L, u'a': 16L}]
I'd like to extract values out of it.
我想从中提取值。
i.e. [15, 9, 16]
IE [15, 9, 16]
So I tried:
所以我试过:
result_list = [int(v) for k,v in qs.items()]
But instead, I get this error:
但相反,我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'items'
I'm wondering why this happens and how to fix it?
我想知道为什么会发生这种情况以及如何解决它?
采纳答案by Ksir
result_list = [int(v) for k,v in qs[0].items()]
qs is a list, qs[0] is the dict which you want!
qs 是一个列表, qs[0] 是你想要的字典!
回答by SIslam
Dictionary does not support duplicate keys- So you will get the last key i.e.a=16
but not the first key a=15
字典不支持重复键 - 所以你会得到最后一个键,即a=16
但不是第一个键a=15
>>>qs = [{u'a': 15L, u'b': 9L, u'a': 16L}]
>>>qs
>>>[{u'a': 16L, u'b': 9L}]
>>>result_list = [int(v) for k,v in qs[0].items()]
>>>result_list
>>>[16, 9]
回答by Jasper Xu
items is one attribute of dict object.maybe you can try
items 是 dict 对象的一个属性。也许你可以试试
qs[0].items()
回答by ozgur
More generic way in case qs
has more than one dictionaries:
如果qs
有多个字典,则更通用的方法:
[int(v) for lst in qs for k, v in lst.items()]
--
——
>>> qs = [{u'a': 15L, u'b': 9L, u'a': 16L}, {u'a': 20, u'b': 35}]
>>> result_list = [int(v) for lst in qs for k, v in lst.items()]
>>> result_list
[16, 9, 20, 35]
回答by Noah
You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.
您在列表中有一本字典。您必须首先从列表中提取字典,然后处理字典中的项目。
If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:
如果您的列表包含多个字典,并且您希望每个字典中的值存储在列表中,请执行以下操作:
result_list = [[int(v) for k,v in d.items()] for d in qs]
Which is the same as:
这与以下内容相同:
result_list = []
for d in qs:
result_list.append([int(v) for k,v in d.items()])
The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:
以上将把每个字典中的值保存在他们自己单独的列表中。如果您只想要一个大列表中的所有值,您可以这样做:
result_list = [int(v) for d in qs for k,v in d.items()]
回答by Galax
If you don't care about the type of the numbers you can simply use:
如果你不关心数字的类型,你可以简单地使用:
qs[0].values()