Reputation: 616
I'm sorry if this is a stupid question but I've been thinking about it a lot and looked through Jinja docs but so far to no avail. Short background: I've just completed Udacity's CS101 and CS253 and am about to help a friend build a booking system for a yoga studio. It's all on Google Appengine, just like
I want to have a list of available yoga classes similar to this:
Monday
Dynamic Yoga with Mary 6pm
Soft yoga with Susie 8pm
Wednesday
Hatha yoga with Bob 5pm
Hot yoga with Alice 7pm
So I want to fetch the list of classes, then see if there is a yoga class on Monday. If there is one I add 'Monday' to the list and all the Monday classes, and so on with all the other days. Like this:
day_output1 = ['Monday',['Dynamic Yoga with Mary 6pm'],['Soft yoga with Su..']]
day_output2 = ['Wednesday',['Hatha yoga with Bob 5pm'],['Hot yoga with Al...']]
And then add these to a list for the whole week, which is then sent to the template:
weekly_classes = [day_output1, day_output2]
Right now I'm getting a KeyError, which means it doesnt find the Key, but I dont understand why?
File "/Users/username/YogaSchemat/yogaschema/main.py", line 113, in get
day = d[n]
KeyError: 1
With this code... Thanks in advance guys!
d = {
"1": 'Monday',
"2": 'Tuesday',
"3": 'Wednesday',
"4": 'Thursday',
"5": 'Friday',
"6": 'Saturday',
"7": 'Sunday'
}
def get_classes():
yoga_classes = Schema.all() #appengine DB request
if yoga_classes:
weekly_classes = [] #list that will be sent to template
for n in range(1,8):
for e in yoga_classes:
if e.weekday == n:
day = d[n] #getting weekday from d
class_details = [] #
class_details.append(e)
day_output = [day,class_details]
weekly_classes.append(day_output)
self.response.out.write(weekly_classes)
Upvotes: 1
Views: 1248
Reputation: 1122172
You are using string keys in your d
mapping, but are looking up a integer instead.
In this case, you should use a list instead:
d = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# ...
for n in range(7):
day = d[n]
with n
between 0 and 6, mapping directly to the names of the week at those positions in the d
list.
Alternatively, you could use integers as keys instead:
d = {
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday'
}
but since your keys are sequential, you may as well save the space.
Upvotes: 1