0

I'm coming from PHP to python.

In PHP i do this:

$result = array();

foreach($videos as $video) {
  $result[] = array("title"=>$video->title,"description"=>$video->title);
}

print_r($result);

Now when i try this in python flask i get an error We're sorry, but something went wrong: Web application could not be started

result = {}

for video in videos:
    title = video['title']
    description = video['description']
    content = {'title':title, 'description': description}
    result[] = content

How do i solve?

Here is full function

@app.route("/add_channel", methods=['POST'])
def add_channel():
    if request.method == "POST":
        id=request.form['channel']
        videos = get_channel_videos(id)

         result = []
         for video in videos:
             result.append({'id': video['id'], 'title': video['snippet']['title']})
    return result
user892134
  • 3,078
  • 16
  • 62
  • 128

1 Answers1

1

If your final result is a list of dictionaries, that last line would be

result.append(content)

More concisely that could be achieved in a list comprehension

result = [{'title': video['title'], 'description': video['description']} for video in videos]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • tried `result.append(content)` and get this error **AttributeError: 'dict' object has no attribute 'append'** – user892134 Jun 02 '20 at 18:51
  • 2
    just change result = {} to result = [], result = {} declares a dictionary – Henrique Forlani Jun 02 '20 at 18:52
  • You would use list initialization before the loop `result = []` otherwise `{}` creates a dictionary – Cory Kramer Jun 02 '20 at 18:52
  • Still get an error ** TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.** – user892134 Jun 02 '20 at 18:53
  • I've tried all suggestions but still get an error when i return the result. – user892134 Jun 02 '20 at 19:00
  • Can you provide some more context? You mentioned `flask` but what specific function are you calling that you are trying to pass `result` to? – Cory Kramer Jun 02 '20 at 19:01
  • @user892134 Follow this link https://stackoverflow.com/questions/56960188/flask-is-returning-typeerror-the-view-function-did-not-return-a-valid-response/56962069 – Mayank Porwal Jun 02 '20 at 19:02