🐍 Loops in Python
Let's say you have a books
array:
# data['books']:
[
{ "name": 'Book 1', "price": 44.99, "qty": 1 },
{ "name": 'Book 2', "price": 9.99, "qty": 3 },
{ "name": 'Book 3', "price": 24.99, "qty": 2 }
]
"For" loops
At the post-processing step you may want to add 3 fields: In each book item add a total
and formatted_total
fields and calculate the order_total
amount.
# Option 1. "For" loop
total = 0
for book in data['books']:
book['total'] = book['price'] * book['qty']
book['formatted_total'] = '$' + str(book['total'])
total += book['total'] # accumulate order total
data['order_total'] = total
"For" loops with indexes
Alternatively, you can use a "for" loop with indexes:
# Option 2. "For" loop with indexes
total = 0
for index, book in enumerate(data['books']):
book_total = book['price'] * book['qty']
data['books'][index]['total'] = book_total
data['books'][index]['formatted_total'] = '$' + str(book_total)
total += book_total
data['order_total'] = total
"For" loops with range
... or using the range
function:
# Option 3. "For" loop with range
total = 0
books_cnt = len(data['books']) # books_cnt = 3
for ind in range(0, books_cnt):
book = data['books'][ind]
book['total'] = book['price'] * book['qty']
book['formatted_total'] = '$' + str(book['total'])
total += book['total']
data['order_total'] = total
Now the data
dictionary should look like this:
{
"books": [
{
"name": "Book 1",
"price": 44.99,
"qty": 1,
"total": 44.99,
"formatted_total": "$44.99"
},
{
"name": "Book 2",
"price": 9.99,
"qty": 3,
"total": 29.97,
"formatted_total": "$29.97"
},
{
"name": "Book 3",
"price": 24.99,
"qty": 2,
"total": 49.98,
"formatted_total": "$49.98"
}
],
"order_total": 124.94
}
Iterate over fields
Finally, in some complex cases you may want to iterate over each parsed field:
for field_name, field_value in data.items():
# your code goes here
Note: 'While' loops are not supported.