简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM