Home > OS >  python filter function on a list of dictionaries
python filter function on a list of dictionaries

Time:07-16

suppose that I have following result from the api :

[
    {
          "id":"1234",
          "views":132624,
          "rate":"4.43",
          "url":"someurl.com",
          "added":"2022-06-14 16:27:28",
          "default_thumb":{
             "size":"medium",
             "width":640,
             "height":360,
          }
    },
    {
          "id":"1234",
          "views":132624,
          "rate":"4.43",
          "url":"someurl.com",
          "added":"2022-06-14 16:27:28",
          "default_thumb":{
             "size":"medium",
             "width":640,
             "height":360,
          }
    },
    ...
]

and I just want to fetch urls in dictionaries, to do that I tried to filter the list with python filter() function :

fetched_urls = list(filter(lambda video_data: video_data['url'] , videos_data))

but when I print fetched_urls I'll get all of the array without any filter process, is there any way to achieve this filtered array using filter() function ?

CodePudding user response:

You need map instead of filter

CodePudding user response:

filter returns the items if the condition is met. try this:

[a['url'] for a in video_data if 'url' in a]
  • Related