MTplus
MTplus

Reputation: 2391

Filter list of class by property value in python

I have this class ...

class Folder:
    def __init__(self,name,path,id):
        self.name = name
        self.path = path
        self.id = id

I then create a list of x number of the above class, how can I query this list and select a class from this list of class ”Folder” that match a certain id and then print out the ”name” property of the found class?

How can I do that?

Upvotes: 0

Views: 44

Answers (1)

José Rodrigues
José Rodrigues

Reputation: 487

Is this what you are looking for ?




class Folder:
    def __init__(self,name,path,_id):
        self.name = name
        self.path = path
        self.id = _id

 #create dummy objects
 f1 = Folder("item1",'/path1',10)
 f2 = Folder("item2",'/path2',20)
 f3 = Folder("item3",'/path3',30)
 
 #create list 
 files = [f1,f2,f3]

 
 def query(_list,_id):
    
    for l in _list:
        if l.id == _id:
            return(l.name)
    return "Folder with id no.{} not found".format(_id)


Hope this helped! Very naive approach, but it works.

Upvotes: 1

Related Questions