Python:如何从一个字典的字典的列表中删除一个字典?



作为起点,我有这个列表:

product = [
{'pid': '5678', 'stocktotal':'498', 'variantIds':[{'vid':'1', 'stockQuantity':0},{'vid':'2', 'stockQuantity':199},{'vid':'3', 'stockQuantity':299}]},
{'pid': '1234', 'stocktotal':'100', 'variantIds':[{'vid':'4', 'stockQuantity':0},{'vid':'5', 'stockQuantity':100},{'vid':'6', 'stockQuantity':0}]}  
]

如何查询这个字典列表以删除特定的字典,例如,当stockQuantity == 0时,我想删除整个字典,当stocktotal == 0时,我也想删除整个'pid'-字典:

product = [
{'pid': '5678', 'stocktotal':'498', 'variantIds':[{'vid':'2', 'stockQuantity':199},{'vid':'3', 'stockQuantity':299}]},
{'pid': '1234', 'stocktotal':'0', 'variantIds':[{'vid':'5', 'stockQuantity':100},]}  
]

您是否在编写CSV文件之前,同时或之后进行这种数据清理?

我使用了一个奉献函数来执行您想要的过滤器:

  • 过滤掉stockQuantity == 0
  • products.product.variantIds
  • 计算products.product.totalquantity并将product从列表中移除,如果0
product = [
{'pid': '5678', 'stocktotal':'498', 'variantIds':[{'vid':'1', 'stockQuantity':0},{'vid':'2', 'stockQuantity':199},{'vid':'3', 'stockQuantity':299}]},
{'pid': '1234', 'stocktotal':'100', 'variantIds':[{'vid':'4', 'stockQuantity':0},{'vid':'5', 'stockQuantity':100},{'vid':'6', 'stockQuantity':0}]},  
{'pid': '12345', 'stocktotal':'100', 'variantIds':[{'vid':'4', 'stockQuantity':0},{'vid':'5', 'stockQuantity':0},{'vid':'6', 'stockQuantity':0}]}  
]
def remove_stockQuantity_of_zero(products):
new_list = []
for item in products:
new_dict = {}
for k, v in item.items():
if k == "variantIds":
v = list(filter(lambda x: x["stockQuantity"] != 0, v))
new_dict.update({k:v})
new_dict["stocktotal"] = sum([x["stockQuantity"] for x in new_dict["variantIds"]])
if new_dict["stocktotal"] == 0:
continue
new_list.append(new_dict)
return new_list
print(remove_stockQuantity_of_zero(product))
# > [{'pid': '5678', 'stocktotal': 498, 'variantIds': [{'vid': '2', 'stockQuantity': 199}, {'vid': '3', 'stockQuantity': 299}]}, {'pid': '1234', 'stocktotal': 100, 'variantIds': [{'vid': '5', 'stockQuantity': 100}]}]

如果您想将结果存储在csv文件中,那么您当然需要在将其写入文件之前执行此操作。

相关内容

  • 没有找到相关文章

最新更新