【问题标题】:how to iterate a dictionary list and do a value concatenation of each product [closed]如何迭代字典列表并对每个产品进行值连接[关闭]
【发布时间】:2022-01-19 15:35:39
【问题描述】:

晚上好,我是python的初学者,我有一个代表客户历史的对象,代码如下:

history = [
{"email": "afrifran@gmail.com", "product": "pomme", "quantity_product": 12},
{"email": "afrifran@gmail.com", "product": "Viande", "quantity_product": 100},
{"email": "afrifran@gmail.com", "product": "pomme", "quantity_product": 18},
{"email": "afrifran@gmail.com", "product": "orange", "quantity_product": 2},
{"email": "afrifran@gmail.com", "product": "orange", "quantity_product": 3},

{"email": "popo@gmail.com", "product": "fraise", "quantity_product": 2},
{"email": "popo@gmail.com", "product": "fraise", "quantity_product": 8},
{"email": "popo@gmail.com", "product": "banane", "quantity_product": 12},
{"email": "popo@gmail.com", "product": "banane", "quantity_product": 3}]

我希望能够浏览对象,同时将与客户关联的每个产品的值串联起来,现在我已经冻结了几天。

我正在等待这样的输出:

obj = [{"email": "afrifran@gmail.com", "orange": 5, "pomme": 30, "Viande": 100}, {"email": "popo@gmail.com", "fraise": 10, "banane": 15}]

【问题讨论】:

  • 你能提供想要的输出吗?

标签: python-3.x iteration concatenation


【解决方案1】:

您可以使用以下代码:

added_products = []
output = []

# Add quantities of each product associated to the customer
for item in history:
    if not added_products:
        added_products.append(item)

    else:
        for cached_item in added_products:
            if item["email"] == cached_item["email"] and item["product"] == cached_item["product"]:
                cached_item["quantity_product"] += item["quantity_product"]
                break
        else:
            added_products.append(item)

# Create output list
for item in added_products:
    if not output:
        d = {"email": item["email"], item["product"]:item["quantity_product"]}
        output.append(d)

    else:
        for cached_item in output:
            if item["email"] == cached_item["email"]:
                cached_item.update({item["product"]:item["quantity_product"]})
                break
        else:
            d = {"email": item["email"], item["product"]: item["quantity_product"]}
            output.append(d)

print(output)

对于您的输入数据,这将更新:

[{'email': 'afrifran@gmail.com', 'pomme': 30, 'Viande': 100, 'orange': 5}, {'email': 'popo@gmail.com', 'fraise': 10, 'banane': 15}]

【讨论】:

  • 谢谢谢谢
  • 如果这对您有所帮助,您能否给它一个赞成票并将其标记为已接受的答案?谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-02-04
  • 2017-07-13
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2021-02-14
相关资源
最近更新 更多