python-3.x 在由多个字典组成的列表中,每4个字典的相似键值相加

yqkkidmi  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(176)

我有一个字典列表,看起来像这样:

[{'success': 10, 'failed': 15, 'manual': 20},
 {'manual': 5, 'success': 10},
 {},
 {},
 {'success': 20, 'manual': 25, 'failed': 30},
 {'success': 2, 'manual': 4, 'failed': 6},
 {},
 {}]

我想对前四个字典的键值求和,然后再次对后四个字典的键值求和,这最终给我两个字典的输出,求和值如下:

[{'success': 20, 'failed': 15, 'manual': 25},
 {'success': 22, 'manual': 29, 'success': 36}]

有人能帮助我们找到一种方法来实现动态列表吗?

ijnw1ujt

ijnw1ujt1#

您可以对每4行数据进行小计,并将结果存储在列表中,如下所示:

from pprint import pprint

data = [
    {'success': 10, 'failed': 15, 'manual': 20},
    {'manual': 5, 'success': 10},
    {},
    {},
    {'success': 20, 'manual': 25, 'failed': 30},
    {'success': 2, 'manual': 4, 'failed': 6},
    {},
    {}
]

subtotal = {"success": 0, "failed": 0, "manual": 0}
results = []
for count, datum in enumerate(data, 1):
    if count % 4 == 0:
        results.append(dict(subtotal))
        subtotal = {"success": 0, "failed": 0, "manual": 0}
    for key, value in datum.items():
        subtotal[key] += value
        
pprint(results)

输出:

[{'failed': 15, 'manual': 25, 'success': 20},
 {'failed': 36, 'manual': 29, 'success': 22}]

相关问题