Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list of object with condition in Python

Tags:

python

I have a list structure like this:

listpost =
[
   {
      "post_id":"01",
      "text":"abc",
      "time": datetime.datetime(2021, 8, 5, 15, 53, 19),
      "type":"normal",
   },
   {
      "post_id":"02",
      "text":"nothing",
      "time":datetime.datetime(2021, 8, 5, 15, 53, 19),
      "type":"normal",
   }
]

I want to filter the list by text in [text] key if only the [text] has "abc"

so the example will look like this

listpost =
[
   {
      "post_id":"01",
      "text":"abc",
      "time": datetime.datetime(2021, 8, 5, 15, 53, 19),
      "type":"normal",
   }
]

My code:

from facebook_scraper import get_posts

listposts = []

for post in get_posts("myhealthkkm", pages=1):
    listposts.append(post)
print(listposts)


like image 797
johnny2000 Avatar asked Mar 20 '26 18:03

johnny2000


2 Answers

Since you specifically asked about filtering the list you have, you can use filter builtin with lambda to filter out the elements from the list.

>>> list(filter(lambda x: x.get('text', '')=='abc', listpost))

[{'post_id': '01', 'text': 'abc', 'time': datetime.datetime(2021, 8, 5, 15, 53, 19), 'type': 'normal'}]

But I'd recommend to filter it out upfront before actually appending it to the list, to avoid unnecessary computations due to the need to re-iterate the items i.e. appending only the items that match the criteria.

Something like this:

for post in get_posts("myhealthkkm", pages=1):
    if <post match the condition>:
        listposts.append(post)  # append the post
like image 94
ThePyGuy Avatar answered Mar 23 '26 06:03

ThePyGuy


simple like that:

filtered_list = [e for e in listpost if e['text'] == 'abc']
like image 44
balderman Avatar answered Mar 23 '26 08:03

balderman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!