I’m trying to create a dataset to be used by Chart.js. The chart’s x-axis has 26 weekly columns for seven reaction variables. The height of each column is a number of occurrences. The expected result of the code is a dictionary containing a dictionary for each reaction with keys 0 - 25 & values for the height of each column.
The code below initializes the top level dictionary and its constituent dictionaries with key 0 also initialized. The attempt to add further keys stops at 1 and loads that key with remaining data. The code (in its test form):
Am I even close to getting where I want to go?
class ReactionTestCase(TestCase):
def setUp(self):
earliest = Gut.objects.order_by('happened')[0].happened
lastDay = datetime.date.today() - datetime.timedelta(days=1)
delta = lastDay - earliest.date()
weeks = min(math.floor(delta.days/7), 26) # no more than 26 weeks of data
firstDay = datetime.date.today() - datetime.timedelta(days=weeks*7)
self.gut = Gut.objects.order_by('happened').filter(happened__gte=firstDay, happened__lte=lastDay)
self.rxList = list(Reaction.objects.values_list('reaction', flat=True))
def testMultiDictUpdate(self):
g = self.gut
dicts = {}
j = 0 # week increment
# create a dictionary for each reaction
for r in range(len(self.rxList)):
dicts[self.rxList[r]] = {}
dicts[self.rxList[r]][j] = 0
currDate = g[0].happened.date()
eow = currDate + datetime.timedelta(days=7)
for grx in g:
rx = grx.reaction.reaction
dicts[rx][j] += 1
if grx.happened.date() == eow:
eow = grx.happened.date() + datetime.timedelta(days=7)
j += 1
for r in range(len(self.rxList)):
dicts[self.rxList[r]][j] = 0
print(dicts)
Test data results:
{'Barf': {0: 0, 1: 0}, 'Big D': {0: 5, 1: 33}, 'Loose': {0: 0, 1: 45}, 'Mush': {0: 2, 1: 77}, 'Nausea': {0: 0, 1: 10}, 'Normal': {0: 0, 1: 55}, 'Pain, gut': {0: 0, 1: 17}}