Jand
Jand

Reputation: 2727

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?

Upvotes: 22

Views: 209069

Answers (6)

Jasper Xu
Jasper Xu

Reputation: 11

items is one attribute of dict object.maybe you can try

qs[0].items()

Upvotes: 1

Galax
Galax

Reputation: 1431

If you don't care about the type of the numbers you can simply use:

qs[0].values()

Upvotes: 2

Learner
Learner

Reputation: 5302

Dictionary does not support duplicate keys- So you will get the last key i.e.a=16 but not the first key 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]

Upvotes: 0

Noah
Noah

Reputation: 1731

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()]

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52213

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]

Upvotes: 7

Ksir
Ksir

Reputation: 426

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

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

Upvotes: 23

Related Questions