as a startingpoint i have this list:
JavaScript
x
5
1
product = [
2
{'pid': '5678', 'stocktotal':'498', 'variantIds':[{'vid':'1', 'stockQuantity':0},{'vid':'2', 'stockQuantity':199},{'vid':'3', 'stockQuantity':299}]},
3
{'pid': '1234', 'stocktotal':'100', 'variantIds':[{'vid':'4', 'stockQuantity':0},{'vid':'5', 'stockQuantity':100},{'vid':'6', 'stockQuantity':0}]}
4
]
5
how do you query this list of dicts to remove specific dicts, e.g. when stockQuantity == 0 i want to remove the whole dict, i also want to remove the whole ‘pid’-dict when stocktotal == 0:
JavaScript
1
5
1
product = [
2
{'pid': '5678', 'stocktotal':'498', 'variantIds':[{'vid':'2', 'stockQuantity':199},{'vid':'3', 'stockQuantity':299}]},
3
{'pid': '1234', 'stocktotal':'0', 'variantIds':[{'vid':'5', 'stockQuantity':100},]}
4
]
5
do you do this kind of data cleaning before, while or after you write a CSV File of it?
Advertisement
Answer
I went with a dedication function to perform the filters that you want:
- Filter out any
products.product.variantIds
wherestockQuantity == 0
- Calculate the
products.product.totalquantity
and remove theproduct
from the list if 0
JavaScript
1
24
24
1
product = [
2
{'pid': '5678', 'stocktotal':'498', 'variantIds':[{'vid':'1', 'stockQuantity':0},{'vid':'2', 'stockQuantity':199},{'vid':'3', 'stockQuantity':299}]},
3
{'pid': '1234', 'stocktotal':'100', 'variantIds':[{'vid':'4', 'stockQuantity':0},{'vid':'5', 'stockQuantity':100},{'vid':'6', 'stockQuantity':0}]},
4
{'pid': '12345', 'stocktotal':'100', 'variantIds':[{'vid':'4', 'stockQuantity':0},{'vid':'5', 'stockQuantity':0},{'vid':'6', 'stockQuantity':0}]}
5
]
6
7
def remove_stockQuantity_of_zero(products):
8
new_list = []
9
for item in products:
10
new_dict = {}
11
for k, v in item.items():
12
if k == "variantIds":
13
v = list(filter(lambda x: x["stockQuantity"] != 0, v))
14
new_dict.update({k:v})
15
new_dict["stocktotal"] = sum([x["stockQuantity"] for x in new_dict["variantIds"]])
16
if new_dict["stocktotal"] == 0:
17
continue
18
new_list.append(new_dict)
19
20
return new_list
21
22
print(remove_stockQuantity_of_zero(product))
23
# > [{'pid': '5678', 'stocktotal': 498, 'variantIds': [{'vid': '2', 'stockQuantity': 199}, {'vid': '3', 'stockQuantity': 299}]}, {'pid': '1234', 'stocktotal': 100, 'variantIds': [{'vid': '5', 'stockQuantity': 100}]}]
24
If you want to store the result in a csv file, then you certainly need to perform this action before writing it to the file.