Reputation: 19
How do I access dictionaries inside a list?
c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
values = []
for key, value in c.iteritems():
values.append((key, value))
print values
I tried accessing the list using iteritems
but I got an error specifying list does not have iteritems
. Then, I tried using a for loop but I still get an error specifying list indices must be integers
.
Upvotes: 0
Views: 101
Reputation: 25639
Try this:
c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
values = []
for row in c:
for key, value in row.iteritems():
if key == 'name':
values.append((key, value))
print(values)
# gives this
# [('name', 'a'), ('name', 'b'),]
Upvotes: 1
Reputation: 24699
I'm not sure what your desired output is, but the problem is that c
is a list()
of dict()
s, not a dict()
. So if you want to loop over every key and value in each dict in the list, you need two loops:
In [85]: for dictionary in c:
....: for key, value in dictionary.iteritems():
....: values.append((key, value))
....: print values
....:
[('name', 'a')]
[('name', 'a'), ('team', 2000)]
[('name', 'a'), ('team', 2000), ('name', 'b')]
[('name', 'a'), ('team', 2000), ('name', 'b'), ('team', 3000)]
You can also simplify this with a list comprehension:
In [96]: for dictionary in c:
values.extend((key, value) for key, value in dictionary.iteritems())
....:
In [97]: values
Out[97]: [('name', 'a'), ('team', 2000), ('name', 'b'), ('team', 3000)]
Or, simplify it even further, as list.extend()
can take any iterable:
In [112]: for dictionary in c:
values.extend(dictionary.iteritems())
.....:
In [113]: values
Out[113]: [('name', 'a'), ('team', 2000), ('name', 'b'), ('team', 3000)]
And, lastly, we can populate values
with a single line of code using itertools.chain()
, which basically "flattens" multiple iterables into a single iterable (thanks @lvc!):
In [114]: from itertools import chain
In [115]: values = list(chain.from_iterable(d.iteritems() for d in c))
Upvotes: 2
Reputation: 158
"c" is not a dictionary therefore iteritems() will not work. Iterate through the list first to isolate the dictionaries.
>>> c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
... for i in c:
... for k,v in i.items():
... print "key : "+str(k)+' *** '+ "value : "+str(v)
... key : name *** value : a
... key : team *** value : 2000
... key : name *** value : b
... key : team *** value : 3000
Upvotes: 0