簡體   English   中英

按參數分組和詞典列表

[英]Group and sum list of dictionaries by parameter

我有一份我的產品詞典(飲料,食品等),有些產品可能會添加幾次。 我需要通過product_id參數對產品進行分組,並對每個組的product_cost和product_quantity求和,以獲得總產品價格。

我是python的新手,了解如何分組字典列表,但無法弄清楚如何總結一些參數值。

"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]

我需要實現這樣的目標:

"products_list": [
    {
        "product_cost": 38,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 21,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    }
]

你可以試試熊貓:

d = {"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]}
df=pd.DataFrame(d["products_list"])

將dict傳遞給pandas並執行groupby。 然后使用to_dict函數將其轉換回dict。

result={}
result["products_list"]=df.groupby("product_name",as_index=False).sum().to_dict(orient="records")

結果:

{'products_list': [{'product_cost': 176.74,
   'product_id': 2,
   'product_name': 'Apples',
   'product_quantity': 800},
  {'product_cost': 38.0,
   'product_id': 2,
   'product_name': 'Coca-cola',
   'product_quantity': 21}]}

您可以首先對product_name上的字典列表進行排序,然后根據product_name對項目進行分組

然后為每個組計算總產品和總數量,創建最終字典並更新到列表,然后制作最終字典

from itertools import groupby

dct = {"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]}

result = {}
li = []

#Sort product list on product_name
sorted_prod_list = sorted(dct['products_list'], key=lambda x:x['product_name'])

#Group on product_name
for model, group in groupby(sorted_prod_list,key=lambda x:x['product_name']):

    grp = list(group)

    #Compute total cost and qty, make the dictionary and add to list
    total_cost = sum(item['product_cost'] for item in grp)
    total_qty = sum(item['product_quantity'] for item in grp)
    product_name = grp[0]['product_name']
    product_id = grp[0]['product_id']

    li.append({'product_name': product_name, 'product_id': product_id, 'product_cost': total_cost, 'product_quantity': total_qty})

#Make final dictionary
result['products_list'] = li

print(result)

輸出將是

{
    'products_list': [{
            'product_name': 'Apples',
            'product_id': 2,
            'product_cost': 176.74,
            'product_quantity': 800
        },
        {
            'product_name': 'Coca-cola',
            'product_id': 1,
            'product_cost': 38,
            'product_quantity': 21
        }
    ]
}

我個人而言,我會通過唯一標識符將其重新組織到另一個字典中。 此外,如果您仍然需要列表格式,您仍然可以在字典中重新組織它,但您只需將dict.values()轉換為列表即可。 下面是一個功能。

def get_totals(product_dict):
    totals = {}
    for product in product_list["product_list"]:
        if product["product_name"]  not in totals:
            totals[product["product_name"]] = product
        else:

            totals[product["product_name"]]["product_cost"] += product["product_cost"]
            totals[product["product_name"]]["product_quantity"] += product["product_quantity"]

    return list(totals.values())

輸出是:

[
 {
  'product_cost': 38,
  'product_id': 1,
  'product_name': 'Coca-cola', 
  'product_quantity': 21
 },
 {
  'product_cost': 176.74,
  'product_id': 2, 
  'product_name': 'Apples',
  'product_quantity': 800
 }
]

現在,如果您需要它屬於產品列表鍵。 只需將列表重新分配給相同的密鑰即可。 而不是返回list(total.values())

product_dict["product_list"] = list(total.values())
return product_dict

輸出是一個字典,如:

{
 "products_list": [
   {
    "product_cost": 38,
    "product_id": 1,
    "product_name": "Coca-cola",
    "product_quantity": 21,
   },
   {
    "product_cost": 176.74,
    "product_id": 2,
    "product_name": "Apples",
    "product_quantity": 800,

   }
 ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM