Jeroen Rutten
Jeroen Rutten

Reputation: 43

for loop within for loop getting invalid syntax

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

Answers (3)

Jeroen Rutten
Jeroen Rutten

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

cdrom
cdrom

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

noob
noob

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

Related Questions