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..
What I want:
- A better way to check if any of the stores have
data
and their code is200
and if so, the product isReady 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 1:
You can use the any function
is_product_available = any([store['status'] == 200 for store in data['store_data']])
Solution 2:
You can use function any
and a generator expression to do that most efficiently like
is_ready = any(d.get("status", 0) == 200 for d in data['store_data'])
this will return True once it found the first match that is true. So if there are 10_000 entries and the first is already 200, it will only have to check that.