Search code examples
pythonpython-3.xlistdictionarysummarize

Summarizing a python list of dicts


Given the following python list of dictionaries:

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
 '},

]

Produce the following summary of H/M/L per product:

product_issues_summary = [

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

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

Appreciate any feedback.


Solution

  • 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}]