Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get 'list' object has no attribute 'items'?

Using Python 2.7, I have this list:

qs = [{u'a': 15L, u'b': 9L, u'a': 16L}]

I'd like to extract values out of it.

i.e. [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?

like image 860
Jand Avatar asked Nov 27 '15 03:11

Jand


People also ask

What does it mean when object has no attribute?

It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.

What does list object has no attribute replace mean?

The part “'list' object has no attribute 'replace'” tells us that the list object we are handling does not have the replace attribute. We will raise this error if we try to call the replace() method on a list object. replace() is a string method that replaces a specified string with another specified string.

How do I fix No attribute error in Python?

Attribute errors in Python are raised when an invalid attribute is referenced. To solve these errors, first check that the attribute you are calling exists. Then, make sure the attribute is related to the object or data type with which you are working.

What does AttributeError list object has no attribute split mean?

The Python "AttributeError: 'list' object has no attribute 'split'" occurs when we call the split() method on a list instead of a string. To solve the error, call split() on a string, e.g. by accessing the list at a specific index or by iterating over the list.


2 Answers

result_list = [int(v) for k,v in qs[0].items()]

qs is a list, qs[0] is the dict which you want!

like image 114
Ksir Avatar answered Oct 21 '22 15:10

Ksir


More generic way in case qs has more than one dictionaries:

[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]
like image 21
Ozgur Vatansever Avatar answered Oct 21 '22 14:10

Ozgur Vatansever