[Solved] Summarizing a python list of dicts


Here’s something you can try. It uses a collections.defaultdict or collections.Counter to count High, Med and Low for each product, then merges the results at the end.

from collections import defaultdict, Counter

product_issues = [
    {"product": "battery", "High": 0, "Med": 1, "Low": 0},
    {"product": "battery", "High": 1, "Med": 0, "Low": 0},
    {"product": "battery", "High": 1, "Med": 0, "Low": 0},
    {"product": "tape", "High": 1, "Med": 0, "Low": 0},
    {"product": "tape", "High": 1, "Med": 0, "Low": 0},
]

d = defaultdict(Counter)
for product in product_issues:
    levels = {k: v for k, v in product.items() if k != "product"}
    d[product["product"]].update(levels)

print([{**{"product": k}, **v} for k, v in d.items()])

Summarized results:

[{'product': 'battery', 'High': 2, 'Med': 1, 'Low': 0}, {'product': 'tape', 'High': 2, 'Med': 0, 'Low': 0}]

0

solved Summarizing a python list of dicts