纯Python实现字典列表按用户分组的数值求和与报告计数
Python: Group Report Dictionaries by User, Sum Numeric Fields, and Count Reports
Hey, I've got a clean pure-Python solution for your problem—grouping those report dictionaries by user, summing the value and commission fields, and counting the total reports per user. Here's how to do it:
Step-by-Step Implementation
# Your original list of report dictionaries reports = [ {"title": "Report 1", "value": 1000, "commission": 2000, "user": "user_1"}, {"title": "Report 2", "value": 500, "commission": 300, "user": "user_1"}, {"title": "Report 3", "value": 1500, "commission": 300, "user": "user_2"} ] # Create a temporary dictionary to track aggregated data per user grouped = {} for report in reports: user_id = report["user"] # Initialize the user's entry if they're not already in the tracker if user_id not in grouped: grouped[user_id] = { "user": user_id, "value": 0, "commission": 0, "total": 0 } # Update sums and report count grouped[user_id]["value"] += report["value"] grouped[user_id]["commission"] += report["commission"] grouped[user_id]["total"] += 1 # Convert the tracker's values into the final list format result = list(grouped.values()) print(result)
What This Does
- Initialization: We use a dictionary
groupedto keep each user's aggregated data organized by their user ID. This makes lookups fast and avoids duplicates. - Iterate & Aggregate: For each report, we check if the user exists in our tracker. If not, we set up their entry with starting values. Then we add the report's numeric values to their totals and increment the report count.
- Final Format: Converting the dictionary's values to a list gives you exactly the output structure you're looking for.
Output
Running this code will produce:
[{"value": 1500, "commission": 2300, "user": "user_1", "total": 2}, {"value": 1500, "commission": 300, "user": "user_2", "total": 1}]
内容的提问来源于stack exchange,提问作者Douglas Laiber
相关产品推荐
相关产品推荐

