pythonlistdictionary

Match dict values and add a key to the dict if it matchs


I have two lists of dicts.

products = [
  {
    'offer': {
      'name': 'Iphone',
      'sku': '1234'
    }
  },
  {
    'offer': {
      'name': 'Samsung',
      'sku': '5678'
    }
  },
]
prices = [
  {
    'id': '1234',
    'price': {
      'value': 500,
      'currencyId': 'USD'
    }
  },
  {
    'id': '5678',
    'price': {
      'value': 600,
      'currencyId': 'USD'
    }
  }
]

I have to add prices to products with matching them by fields "sku" and "id". I want to get a new list of dicts

[
  {
    'offer': {
      'name': 'Iphone',
      'sku': '1234',
      'value': 500,
      'currencyId': 'USD'
    }
  },
  {
    'offer': {
      'name': 'Samsung',
      'sku': '5678',
      'value': 600,
      'currencyId': 'USD'
    }
  }
]

I tried to do this:

for product, price in zip(products, prices):
    if product.get("offer", {}).get("sku", {}) == price.get("id", {}):
        product.get("offer", {}).update(price.get("price", {}))

but it doesn't works. It updates only 14 products (in the list of 4000 products) and I can't understand why.


Solution

  • I'd recommend to first create a mapping dictionary from the prices list (where keys are id). Then to use this dictionary to create the output:

    products = [
        {"offer": {"name": "Iphone", "sku": "1234"}},
        {"offer": {"name": "Samsung", "sku": "5678"}},
    ]
    
    prices = [
        {"id": "1234", "price": {"value": 500, "currencyId": "USD"}},
        {"id": "5678", "price": {"value": 600, "currencyId": "USD"}},
    ]
    
    prices_dict = {d["id"]: d["price"] for d in prices}
    
    products = [
        {"offer": {**d["offer"], **prices_dict.get(d["offer"]["sku"], {})}}
        for d in products
    ]
    print(products)
    

    Prints:

    [
        {"offer": {"name": "Iphone", "sku": "1234", "value": 500, "currencyId": "USD"}},
        {"offer": {"name": "Samsung", "sku": "5678", "value": 600, "currencyId": "USD"}},
    ]