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?
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.
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.
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.
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.
result_list = [int(v) for k,v in qs[0].items()]
qs is a list, qs[0] is the dict which you want!
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With