We have our records data structure set up as
RECORDS. Now let’s look at how to insert values appropriately into our so called database (data structure).
If you were able to solve the exercise in the previous post then you’re half way through this.
def insert_record(name,subject,score): RECORDS[name][subject].append(score)
Looks simple right? One-liner. Let’s discuss what’s really going on there.
Taking a closer look at
RECORDS, we can tell it’s a dictionary which has keys being the names of our students. This means by using the names of students, we can fetch the corresponding values of those students. Try this code in your editor
print RECORDS[wendy]. What did you get? I’m not saying it so go try it if you haven’t 😀
wendy as example, we can tell that
RECORDS[wendy] is also a dictionary which has it’s keys being the subjects. We can go ahead and get the values of the subjects like this
RECORDS[wendy][music]. This value is a list. And this is where the mark of the student for that trimester, for that subject will be saved. We call
append on this
list to insert the value.
Insert function in action
insert_record(jake,math,88) print RECORDS #check to see jake's records
This gracefully inserts 88 into the math record of Jake. Now what if the math teacher had all the marks on a sheet and has to enter them all. Take a look at this:
#MATH RECORDS FOR FIRST TRIMESTRE #sheet = [[bill,20],[jake,90],[wendy,85],[sandy,77]] def insert_all_records(sheet,subject): for record in sheet: insert_record(record,subject,record)
If you visualize the comment
sheet = [[bill,20],[jake,90],[sandy,77]] , you can see that it looks like an excel sheet with two columns: name, score. And three rows.
The code above takes this data and inserts it one after the other, making use of the
insert_record() function we looked at earlier.
As you can see, each record inside the
sheet variable is a
list with name at index 0 and score at index 1.
Let’s take a look at an example:
# INSERT ALL RECORDS FOR MATH math_sheet = [[jake, 77], [gerald, 89], [nat, 43], [pius, 65], [wendy, 75],[bill, 32], [vanessa, 46], [freda, 87],[joan, 54], [sandy, 88]] insert_all_records(math_sheet,math) print RECORDS #check the math records
Create (or alter data) and pass it for other subjects till you fill all subjects with their first trimester score.
After inserting records, subject by subjects for all three trimesters (or even just one or two trimesters), we may want to change some marks. Humans are prone to error, come on, how can we not be considerate?!
In our next lesson, we’ll look at how to update existing records. You may want to try creating the functions needed, on your own before we meet next time.