Hopefully I can explain what I am trying to accomplish. I have no problem achieving my result, but I know that this is probably not the best way to do it.
I have a table with some entries by date. I am trying to take those entries from the current month, and arrange them into a list by week, and then sum a value from the table for each day of the week. The end result would look something like this:
{44: {4: Decimal('2.80'), 5: Decimal('6.30')}, 45: {1: Decimal('8.90'), 2: Decimal('10.60')}}
I have a solution. But, I know this is not the best way to do it. Any ideas about how to make this better?
#Queries the database and returns time objects that have fields 'hours' and 'date'
time = self.month_time()
r = {}
for t in time:
#Get the week of the year number
week = t.date.isocalendar()[1]
#Get the day of the week number
day = t.date.isoweekday()
if week not in r:
r.update({week:{}})
if day not in r[week]:
r[week][day] = 0
r[week][day] = r[week][day] + t.hours
I think you are probably looking for the defaultdict
. A defaultdict
is just like a dictionary, except when a KeyError would be thrown with dict
, the factory function given upon initialization is used to create an initial value.
In your case, you'll need a defaultdict
for days
nested inside one for weeks
. I think this will work for you:
from collections import defaultdict
r = defaultdict(lambda: defaultdict(int))
for t in time:
week = t.date.isocalendar()[1]
day = t.date.isoweekday()
r[week][day] += t.hours