skip to Main Content

I am trying to create new products for my Woocommerce store but I’m struggling with the images. I am iterating through all the products in my excel sheet with a for loop. In each loop I’m uploading all the pictures of a product to WordPress. It then returns the image IDs which I add to a list, for example:

img_id_list = [203, 204, 205, 206, 207, 208]

When it comes to defining the product data, I have to attribute the image ID to the product data like this:

product_data = {
        "name": name,
        "description": description,
        "short_description": short_description
        "sku": SKU,
        "regular_price": selling_price,
        "categories": [
            {
                "id": category}]
        "images": [
        {
            "id": img_id_list[0]
        },
        {
            "id": img_id_list[1]
        }
    ]
}
         
      

As you can see, the problem is that I have to create a new "id" attribute within the product_data variable for each image ID. However, not all products in my for loop have the same amount of images (some have 5, while others might have 2). How can I assign all image ID’s to the product data when the amount of image ID’s varies each loop? Is there a pythonic way to solve this problem?

2

Answers


  1. Chosen as BEST ANSWER

    I found an answer so i'll just post it here in case someone has the same problem:

    You can simply create a function like this:

    def idfinder(img_id_list):
        locallist = list()
        for i in img_id_list:
            localdict = {"id": i}
            locallist.append(localdict)
        return locallist
    

  2. more pythonic way:

    product_data = {
        ...
        "images": [{"id": id} for id in img_id_list],
        ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search