Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Easiest way to filter a list

I have an API that returns store availability for an Item, The product should be considered Ready To Purchase if any of the stores return 200, and Not Ready to every other status codes (Including 404).

{
  "status": 200,
  "sku": "svk__21w",
  "store_data": [
    {
      "status": 404,
      "reason": "no product found, or product is not available, or not in inventory"
    },
    {
      "status": 404,
      "reason": "no product found, or product is not available, or not in inventory"
    },
    {
      "status": 404,
      "reason": "no product found, or product is not available, or not in inventory"
    }
  ]
}

Now, In my code, To check If this product is indeed Ready To Purchase or not, I use a for loop:

is_product_available = False
for store in data['store_data']:
   if 'data' in store and store['status'] == 200:
        print("Product state is ready to purchase")

        is_product_available = True
   else:
        print("Product state is not ready to purchase")

Which works, But I think it’s just bad design, In the future, With more stores opening..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I want:

  • A better way to check if any of the stores have data and their code is 200 and if so, the product is Ready To Purchase.

Example of a Ready To Purchase product:

store_data: 
   store_1: 404
   store_2: 404
   store_3 200

Example of a Not Ready To Purchase product:

store_data: 
   store_1: 404
   store_2: 404
   store_3 404

>Solution :

You can use the any function

is_product_available = any([store['status'] == 200 for store in data['store_data']])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading