总结词典列表

发布于 2025-02-12 17:57:10 字数 1729 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清泪尽 2025-02-19 17:57:10

您可以利用 group> groupby在Itertools模块中。因此,基本上,您可以根据“ CAT_ID”的值对字典进行分组。在“ for循环”中,您将获得第一个字典并将其添加到最终结果列表中,然后对于组中的其余字典就存在,您只需增加“ tocks”的值。

from itertools import groupby

given_list = [
    {"cat_id": 1, "category": "red", "items": 1},
    {"cat_id": 1, "category": "red", "items": 3},
    {"cat_id": 2, "category": "yellow", "items": 2},
    {"cat_id": 2, "category": "yellow", "items": 4},
    {"cat_id": 2, "category": "yellow", "items": 6},
    {"cat_id": 3, "category": "green", "items": 99},
]

outcome = []
for _, g in groupby(given_list, key=lambda x: x["cat_id"]):
    outcome.append(next(g))
    for d in g:
        outcome[-1]["items"] += d["items"]

要注意的一件事是,您的数据应该已经通过这种方法进行对。如果不是,您需要先排序它。这就是groupby的工作方式。

You can take advantage of groupby in itertools module. So basically you group the dictionaries based on the value of the "cat_id". In the for loop, you get the first dictionary and add it to the final result list, then for the rest of the dictionaries exist in the group, you just increment the value of "items".

from itertools import groupby

given_list = [
    {"cat_id": 1, "category": "red", "items": 1},
    {"cat_id": 1, "category": "red", "items": 3},
    {"cat_id": 2, "category": "yellow", "items": 2},
    {"cat_id": 2, "category": "yellow", "items": 4},
    {"cat_id": 2, "category": "yellow", "items": 6},
    {"cat_id": 3, "category": "green", "items": 99},
]

outcome = []
for _, g in groupby(given_list, key=lambda x: x["cat_id"]):
    outcome.append(next(g))
    for d in g:
        outcome[-1]["items"] += d["items"]

One thing to note is that your data should already be sorted with this approach. If not you need to first sort it. This is how groupby works.

久随 2025-02-19 17:57:10

我将使用 pandas dataFrame

import pandas as pd
df = pd.DataFrame(data=given_list)
new_dict = (
   df.groupby(["cat_id","category"])
     .sum().reset_index()
).to_dict(orient="records")

new_dict的输出将是

[{'cat_id': 1, 'category': 'red', 'items': 4},
 {'cat_id': 2, 'category': 'yellow', 'items': 12},
 {'cat_id': 3, 'category': 'green', 'items': 99}]

I would use pandas dataframe

import pandas as pd
df = pd.DataFrame(data=given_list)
new_dict = (
   df.groupby(["cat_id","category"])
     .sum().reset_index()
).to_dict(orient="records")

the output for new_dict will be

[{'cat_id': 1, 'category': 'red', 'items': 4},
 {'cat_id': 2, 'category': 'yellow', 'items': 12},
 {'cat_id': 3, 'category': 'green', 'items': 99}]
莫多说 2025-02-19 17:57:10

python为您提供了 defaultdict 的简单直截了当的答案

given_list = [
{"cat_id": 1, "category": "red", "items": 1},
{"cat_id": 1, "category": "red", "items": 3},
{"cat_id": 2, "category": "yellow", "items": 2},
{"cat_id": 2, "category": "yellow", "items": 4},
{"cat_id": 2, "category": "yellow", "items": 6},
{"cat_id": 3, "category": "green", "items": 99},]

def nested_dict(n, type):
if n == 1:
    return defaultdict(type)
else:
    return defaultdict(lambda: nested_dict(n-1, type))

from collections import defaultdict
output_list = []
tmp = nested_dict(2, int)

for i in given_list:
    for key, value in i.items():
        if key == "cat_id":
            tmp_key_1 = str(value)
        elif key == "category":
            tmp_key_2 = str(value)
        else:
            tmp[tmp_key_1][tmp_key_2] += value

for key, value in tmp.items():
    for key_1, value_1 in value.items():
        output_list.append({"cat_id":key, "category":key_1, "items":value_1})

,最后,您的 output_list 将具有预期的结果。

Python is providing you the easy and straight forward answer with the defaultdict

given_list = [
{"cat_id": 1, "category": "red", "items": 1},
{"cat_id": 1, "category": "red", "items": 3},
{"cat_id": 2, "category": "yellow", "items": 2},
{"cat_id": 2, "category": "yellow", "items": 4},
{"cat_id": 2, "category": "yellow", "items": 6},
{"cat_id": 3, "category": "green", "items": 99},]

def nested_dict(n, type):
if n == 1:
    return defaultdict(type)
else:
    return defaultdict(lambda: nested_dict(n-1, type))

from collections import defaultdict
output_list = []
tmp = nested_dict(2, int)

for i in given_list:
    for key, value in i.items():
        if key == "cat_id":
            tmp_key_1 = str(value)
        elif key == "category":
            tmp_key_2 = str(value)
        else:
            tmp[tmp_key_1][tmp_key_2] += value

for key, value in tmp.items():
    for key_1, value_1 in value.items():
        output_list.append({"cat_id":key, "category":key_1, "items":value_1})

Finally, your output_list will have the expected result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文