Home > Net >  python how to combine two list by matching parent_id
python how to combine two list by matching parent_id

Time:01-21

variation_product have attribute parent_product_id and I want to combine parent_product and variation_product into a single list by matching parent_product_id attribute. how to do that?

here my data look like:

    {
      "parent_product": [
        {
          "parent_product_id": "sku01"
          "product_title": "product1",
          
      ],
      "variation_product": [
        {
        "variation_product_id": "001",  
        "parent_product_id": "sku01" 
        "user_id": "1"
          
        }
      ],
      "parent_product": [
        {
          "parent_product_id": "sku02"
          "product_title": "product2",
          
      ],
      "variation_product": [
        "variation_product_id": "002",  
        "parent_product_id": "sku02"
        "user_id": "2"
      ]
} 

my expected result will be:

{
   "parent_product": [
    "parent_product_id": "sku01"
    "product_title": "product_1",
    "variation_product_id": "001",
    "user_id": "1"
      ],
    "parent_product": [
    "parent_product_id": "sku02"
    "product_title": "product2",
    "variation_product_id": "002",
     "user_id": "2"

      ],
}

CodePudding user response:

result = {}
for parent in data["parent_product"]:
    parent_id = parent["parent_product_id"]
    parent_title = parent["product_title"]
    variations = [v for v in data["variation_product"] 
if v["parent_product_id"] == parent_id]
    result[parent_id] = {"product_title": parent_title, "variations": 
variations}

This code will iterate through the parent_product data, and for each parent product, it will find the corresponding variation_product by matching the parent_product_id attribute. Then it will create a new dictionary with the parent_product_id as the key, and the product_title and variations as the values.

CodePudding user response:

Using product from itertools

import itertools

combined_data = {} 
combined_data["parent_product"] = [
    {**pp, **vp}
    for pp, vp in itertools.product(data["parent_product"], data["variation_product"])
    if pp["parent_product_id"] == vp["parent_product_id"]
    ]
    
print(combined_data)   

Note: Your expected output is not even properly constructed. You should have only one parent_product as a list of dictionaries containing different attributes like the below output:

{
    'parent_product': [
        {
            'parent_product_id': 'sku01', 
            'product_title': 'product1', 
            'variation_product_id': '001', 
            'user_id': '1'
            
        }, 
        {
            'parent_product_id': 'sku02', 
            'product_title': 'product2', 
            'variation_product_id': '002', 
            'user_id': '2'
            
        }
    ]
    
}
  • Related