Search code examples
pythonoopcontains

python: searching list of objects for certain attribute value


I have an class for twitter tweets that looks like this, I'm thinking there probably is a good fix for this

class tweet:

    def __init__(self, userName, likes, replys, retweets, message, ID):
        self.userName = userName
        self.likes = likes
        self.replys = replys
        self.retweets = retweets
        self.message = message
        self.lenMessage = len(self.message)
        self.mentions = self.message.count('@')
        self.hastags = self.message.count('#')
        self.ID = ID

And in my main class I have a list of this kind of object. I want to be able to look in this list whether there are any in the tweets in the list that have a certain ID, and i just cant figure out exactly how to formulate this:

from Students import tweet


listoftweets = []

t1 = tweet("ding", 100, 5, 1,"a message",   1906961683)
t2 = tweet("dong" ,5, 5, 5, "another message", 190696969)
t3 = tweet("bang", 1, 1, 1, "anew message",2003)
t4 = tweet("fest" ,3, 3, 3,"a message", 1930)
listoftweets.append(t1)
listoftweets.append(t2)
listoftweets.append(t3)
listoftweets.append(t4)



# now if i wanted to check if there is a object with the attribute ID = 2003
#how would i do this?
if listoftweets.__contains__():
    print("the list does contain specified ID")

Thank you all very much


Solution

  • Is this what you are looking for?

    for l in listoftweets:
        if l.ID == "###":  # ID to be matched
            print("List does contain specified ID")
            break