I have JSON documents of this type:
{
name : 'John',
age : 30,
counts : [
{day : monday, pay : 75, extra : 33} ,
{day : tuesday, pay : 69, extra : 12} ,
{day : sunday, pay : 42, extra : 0} ]
}
I want to iterate through them and perform actions. I have created a variable “a” as an attempt to iterate:
x = [2, 67, 53, 21, 5, ... ... ]
for i in db.docs.find():
a = 0
while a <= len(i['counts']):
...
x.append(i['counts'][a]['extra'])
...
total = ...
...
a = a + 1
db.docs.update({'id': i['id']}, {'$set':{"counts.a.total":total}})
How can I make Python accept “a” as a list index?
Thank you for your help.
This is the error message:
Traceback (most recent call last):
x.append(i['counts'][a]['extra'])
IndexError: list index out of range
You could just use a for loop:
If you must use a while loop, make sure the index is strictly lower than the length.