Open the project you created in the 'Creating Our Table' lesson. If you haven't completed that lesson yet, please go back and do it first.
Let's start by creating a list of data to add to our table. We'll use the example of a list of superheroes and their powers. Create a list of dictionaries like this:
data = [
{'Name': 'Superman', 'Power': 'Super Strength'},
{'Name': 'Batman', 'Power': 'Gadgets'},
{'Name': 'Wonder Woman', 'Power': 'Lasso of Truth'},
{'Name': 'Flash', 'Power': 'Super Speed'}
]
Now we'll add the data to our table. Create a function called add_data_to_table that takes the table and the data as arguments. Inside the function, loop through the data and create a new row for each dictionary. Then, add the values from the dictionary to the row's cells:
def add_data_to_table(table, data):
for item in data:
row = table.addRow()
row[0].text = item['Name']
row[1].text = item['Power']
Now that we have our function, it's time to call it and see the magic happen. Add the following line at the end of your code:
add_data_to_table(table, data)
You're previewing this lesson. Get full access to this lesson and hundreds more — each one ready to teach, with interactive activities, printable resources and pupil progress tracking built in.