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
Solution 1:
result_list = [int(v) for k,v in qs[0].items()]
qs is a list, qs[0] is the dict which you want!
Solution 2:
More generic way in case qs
has more than one dictionaries:
[int(v) forlstin qs fork, 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]
Solution 3:
If you don't care about the type of the numbers you can simply use:
qs[0].values()
Solution 4:
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()]
Solution 5:
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]
Post a Comment for "Why I Get 'list' Object Has No Attribute 'items'?"