mohammad
mohammad

Reputation: 5

python filter function on a list of dictionaries

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 ?

Upvotes: 0

Views: 164

Answers (2)

bpfrd
bpfrd

Reputation: 1025

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

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

Upvotes: 0

Tikhon Petrishchev
Tikhon Petrishchev

Reputation: 304

You need map instead of filter

Upvotes: 1

Related Questions