Filter list of object with condition in Python

Viewed 2336

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)


5 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

simple like that:

filtered_list = [e for e in listpost if e['text'] == 'abc']

If you want to filter elements that are exactly "abc"

new_list = [el for el in listpost if el["text"]=="abc"]

If you want to keep elements that starts with "abc"

new_list = [el for el in listpost if el["text"].startswith("abc")]

If you want to keep elements that contains the "abc" substring

new_list = [el for el in listpost if "abc" in el["text"]]

A good pythonic solution is already given, but here's another solution closer to what you were trying:

from facebook_scraper import get_posts

listposts = []
wanted = "abc"  # wanted post
for post in get_posts("myhealthkkm", pages=1):
    if t:=post.get("text", "") == wanted:
        # print("Found", t)
        listposts.append(post) 
    else:
        pass
        # print("Not found")
print(listposts)
 list(filter(lambda x: x['text']=='abc', listpost))

Hope this works

Related