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)
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With