So I have this list of tuples as shown below:
[(21, 2, 10.0),
(21, 104, 20.0),
(22, 1, 371.0),
(22, 104, 742.0),
(23, 1, 114.0),
(23, 104, 228.0),
(25, 1, 2.0),
(25, 104, 2.0)]
The context of each number, in order, is an id, sku_id and quantity. The goal is to go through each batch of tuples with the same ID and do the following:
In the example above, the rows with the id of 25 would match as the row with sku_id being 1 does not have half the quantity as the row with sku_id 104. This should be appended to a final set.
How can I accomplish this?
You could use collections.defaultdict
to make a dictionary of the orders:
all_orders = defaultdict(dict)
for i, sku, qty in data:
all_orders[i][sku] = qty
all_orders
is now:
{
21: {2: 10.0, 104: 20.0},
22: {1: 371.0, 104: 742.0},
23: {1: 114.0, 104: 228.0},
25: {1: 2.0, 104: 2.0}
}
Then just loop through that and find if they meet the criteria
for i, orders in all_orders.items():
if 104 not in orders:
continue
if len(orders) == 1:
print("Needs to be more than one order if sku is 104")
continue
half_104_qty = orders[104] / 2
for qty in orders.values():
if qty < half_104_qty:
continue
else:
print("There must be another order half the quantity of the order with sku 104")