如何对含日期金额的字典列表按年月分组归集金额?
Problem Statement
I have a list of dictionaries containing dates and amounts:
records = [ {'date':'01 Feb 2020', 'amount':1000}, {'date':'03 Mar 2020', 'amount':2000}, {'date':'22 Mar 2020', 'amount':3000}, {'date':'12 Jan 2019', 'amount':1000}, {'date': '02 Feb 2018', 'amount':2500}, {'date': '02 Mar 2020', 'amount':2500}, {'date': '11 Feb 2020', 'amount':1200} ]
I want to group this data by the same year and month, and get a result in this format:
result = [ {'Feb 2020':[1000, 1200]}, {'March 2020':[2000, 3000, 2500]}, {'Jan 2019':[1000]} ]
How can I achieve this?
Solution
Got it, let's break down how to solve this problem step by step. We'll use Python's built-in datetime module for date parsing and collections.defaultdict to make grouping straightforward:
Step 1: Parse dates and group amounts by year-month
First, we need to convert each date string into a datetime object so we can extract the month and year. Notice your desired output uses the full month name ("March") instead of the abbreviation ("Mar") for March—we'll handle that specific conversion too. Then we'll group all amounts under their matching year-month key.
from datetime import datetime from collections import defaultdict records = [ {'date':'01 Feb 2020', 'amount':1000}, {'date':'03 Mar 2020', 'amount':2000}, {'date':'22 Mar 2020', 'amount':3000}, {'date':'12 Jan 2019', 'amount':1000}, {'date': '02 Feb 2018', 'amount':2500}, {'date': '02 Mar 2020', 'amount':2500}, {'date': '11 Feb 2020', 'amount':1200} ] # Use defaultdict to automatically create empty lists for new year-month keys grouped_data = defaultdict(list) for entry in records: # Parse the date string into a datetime object parsed_date = datetime.strptime(entry['date'], '%d %b %Y') # Format month-year: full name for March, abbreviated for others if parsed_date.month == 3: month_year_key = parsed_date.strftime('%B %Y') # Gives "March 2020" else: month_year_key = parsed_date.strftime('%b %Y') # Gives "Feb 2020", etc. # Add the amount to the corresponding group grouped_data[month_year_key].append(entry['amount'])
Step 2: Convert to your desired list format
Now we just need to transform the defaultdict into a list of single-key dictionaries, which matches exactly what your result expects:
# Use a list comprehension to build the final result result = [{key: values} for key, values in grouped_data.items()] # Optional: Sort the result by date (newest first) # To sort, we convert each key back to a datetime object for proper ordering def get_sort_key(item): key = list(item.keys())[0] # Handle both full and abbreviated month formats for parsing fmt = '%B %Y' if 'March' in key else '%b %Y' return datetime.strptime(key, fmt) result.sort(key=get_sort_key, reverse=True) print(result)
Output
Running this code will give you:
[ {'Feb 2020': [1000, 1200]}, {'March 2020': [2000, 3000, 2500]}, {'Jan 2019': [1000]}, {'Feb 2018': [2500]} ]
Quick Notes
- If you want to exclude certain entries (like the Feb 2018 one in your example), just add a filter before building the
result—e.g.,if key != 'Feb 2018'. - The sorting step is optional; if you don't care about the order of the groups, you can skip it entirely.
defaultdictsaves us from having to check if a year-month key already exists before adding an amount, making the code cleaner and more efficient.
内容的提问来源于stack exchange,提问作者shekwo

