简体   繁体   中英

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 ?

您需要map而不是filter

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM