Reputation: 43
Hi I am quite new to python and struggling with creating a for loop within a for loop. I want the bottom 3 lines to loop. Many thanks!
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"],
restaurant['reviews'][0]['text'],
restaurant['reviews'][1]['text'],
restaurant['reviews'][2]['text'],
])
The way I tried it is as follows:
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"],
for reviews in restaurant['reviews']:
reviews['text'],
])
Upvotes: 0
Views: 72
Reputation: 43
Thanks! This indeed worked:
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]] +
[rev["text"] for rev in restaurant["reviews"]]
)
Upvotes: 0
Reputation: 599
you can't use a for loop inside an expression.
This should works :
for restaurant in sorted_list:
# create the list to append
row = [
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]
]
# expend this list with 'reviews'
for review in restaurant['reviews']:
row.append(review['text'])
# append the list to wks_res
wks_res.append_row(row)
alternatively you can use list comprehension
row = [
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]
] + [review['text'] for review in restaurant['reviews']]
Upvotes: 1
Reputation: 141
This should work. Watch out for those brackets, they are rearranged on purpose. Check out list comprehension on Internet for more info about this.
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]] +
[rev["text"] for rev in restaurant["reviews"]]
)
Upvotes: 3