Search code examples
pythonreportlab

How to extract elements from a list of tuples in python for a ReportLab table?


I have a problem with creating a reportlab table containing elements from a list of tuples.

Having the input:

meta= [('#Instances (Test)', '250'), ('#Instances (Train)', '250')]

I intuitively thought of writing it that way:

for key, value in meta:
    data = [['Solver', '%s'%(solver_name)],
             ['%s'%(key), '%s'%(value)],
              ['%s'%(key), '%s'%(value)]]
meta_data = Table(data, colWidths=None, rowHeights=None, style=None, splitByRow=1,
                  repeatRows=0, repeatCols=0)

But it only considers the last tuple making ('#Instances (Train)', '250') appear in both rows. Any ideas on what I did wrong?


Solution

  • You are only getting the last key, value from your input because every time in the loop you are changing the whole data variable. What you have meant is propably this

    data = []
    for key, value in meta:
        data.append([['Solver', solver_name],[key, value]])
    meta_data = Table(data, colWidths=None, rowHeights=None, style=None, \
      splitByRow=1,repeatRows=0, repeatCols=0)
    

    In the above code, I initialize data variable as an empty list, then go through each tuple in meta, assigning that tuple[0] as key and tuple[1] as value. The only thing that is done with those variables is we append them to the list we initialized at the start.