Search code examples
pythonpython-3.xpython-class

Check if value in an array of objects


I recently wrote a code that had all attributes stored separately in different arrays like

order_id = []
order_name = []
order_products = []
order_total = []

And when importing new orders through an API request I would check if I already have that order by doing

if new_order_id in order_id:
    # do new order stuff

Now I want to change the code so that order is a class that has id, name, products and total as attributes and all orders are stored in an array called orders. Is there an easy way to check if the new order id matches the id of any order objects in the orders array?


Solution

  • class oder():
        def __init__(self, id, name, products, total):
            self.id = id
            self.name = name
            self.products = products
            self.total = total
        
    oders=[]# Class objects are here
    
    if new.id in [oder.id for oder in oders]:
        #Place an Order