Brock Hennings
Brock Hennings

Reputation: 1

Python: Filtering a List by a Condition into a new List

I have a list variable my_list which has entries of dictionaries.

my_list = [{'tweet':'tweet_text1','author':'twitter_name1'},
{'tweet':'tweet_text2','author':'twitter_name2'},
{'tweet':'tweet_text3','author':'twitter_name3'}]

I need to filter out any results under the key 'tweet' that are less than 10 characters long, and store those values in a new variable my_list_cleaned

I also need to know the number of items that have been removed, and print that separately.

I've written a function that does something similar for another section, however it doesn't appear to work lists

def filters(x): 
    return [a for a in x.split() if len(a) > 9]

Upvotes: 0

Views: 85

Answers (3)

T.Woody
T.Woody

Reputation: 1218

You just iterate through the list and check the value off of the given key, 'tweet'.

def f(l):
 r = []
 for d in l:
  if len(d['tweet'])<=10:
   continue
  r.append(d)
 return r

You can use the above function to return your list. From there, you will want to make another function that compares the length of the original vs. the length of the new.... diff = len(_old) - len(_new).

Upvotes: 0

user2731223
user2731223

Reputation: 114

Why don't you just loop over each element in my_list and check the 'tweet' key? Something like this:

  def filter(l):
    for d in l:
      if(len(d['tweet']) > 10):
        #do something

Upvotes: 0

rdas
rdas

Reputation: 21275

Remove all the short tweets using a list-comprehension.

my_list_cleaned = [v for v in my_list if len(v['tweet']) >= 10]

You can get the number of tweet removed by comparing the length of the lists

removed = len(my_list) - len(my_list_cleaned)

Upvotes: 1

Related Questions