Hello I'm writing a Django application that reports on daily items purchased. I want to organize the data in a dictionary structure like so..
monthly_items = {
"Apr-27" : [ list of objects purchased on April-27th ]
"Apr-26" : [ list of objects purchased on April-26th ]
"Apr-25" : [ list of objects purchased on April-25th ]
"Apr-24" : [ list of objects purchased on April-24th ]
...
"Mar-27" : [ list of objects purchased on March-27th ]
}
right now my code looks like this (start_date and end_date are configured for last month and today, respectively):
month_dict = {
1: 'Jan',
2: 'Feb',
3: 'Mar',
4: 'Apr',
5: 'May',
6: 'June',
7: 'July',
8: 'Aug',
9: 'Sept',
10: 'Oct',
11: 'Nov',
12: 'Dec',
}
from collections import OrderedDict
monthly_items = OrderedDict()
# pull items from last 30 days
items = Item.objects.filter(create_date__gte=start_date, create_date__lt=end_date).order_by('-create_date')
for item in items:
day = str(month_dict.get(item.create_date.month)) + '-' + str(item.create_date.day)
day_items = monthly_items.get(day, [])
day_items.append(item)
this works great, and I get the dictionary structure that I want, but my problem is that if there are no items purchased on April 24th, there will be no key in the dictionary, and when I print my dict to html, I am missing a Apr-24 column when in reality, I want one but with an empty list. Is there a way to pre-populate an ordered dict with the 30 most recent days as keys (with compatibility to cross months)?