brenda
brenda

Reputation: 803

How to create a table with different number of rows using prettytable module python

I have the following code to generate a table using PrettyTable:

from prettytable import PrettyTable 

# columns names
columns = ["Characters", "FFF", "Job"] 

# lists
lista1 = ["Leanord", "Penny", "Howard", "Bernadette", "Sheldon", "Raj"]
lista2 = ["X", "X", "X", "X", "X", "X", "X"]
lista3 = ["B", "C", "A", "D", "A", "B", "B"]
 
# init table 
myTable = PrettyTable() 
  
# Add data
myTable.add_column(columns[0], [item for item in lista1]) 
myTable.add_column(columns[1], [item for item in lista2]) 
myTable.add_column(columns[2], [item for item in lista3]) 

print(myTable)

And this is the output:

enter image description here

However, what I really want is to create a table with different column sizes (my lists have different lengths). In other words, this is my desired output:

enter image description here

I tried using the code above, however, I'm getting the following error: Exception: Column length 7 does not match number of rows 6!

I would really appreciate your help!!!

Upvotes: 0

Views: 1708

Answers (1)

Matt Miguel
Matt Miguel

Reputation: 1375

Keep all columns the same size by padding the shorter columns with empty strings.


from prettytable import PrettyTable


def column_pad(*columns):
  max_len = max([len(c) for c in columns])
  for c in columns:
      c.extend(['']*(max_len-len(c)))

# columns names
columns = ["Characters", "FFF", "Job"] 

# lists
lista1 = ["Leonard", "Penny", "Howard", "Bernadette", "Sheldon", "Raj","Amy"]
lista2 = ["X", "X", "X", "X"]
lista3 = ["B", "C", "A", "D", "A", "B"]

column_pad(lista1,lista2,lista3)
 
# init table 
myTable = PrettyTable() 
  
# Add data
myTable.add_column(columns[0], lista1) 
myTable.add_column(columns[1], lista2) 
myTable.add_column(columns[2], lista3) 

print(myTable)

+------------+-----+-----+                              
| Characters | FFF | Job |                              
+------------+-----+-----+                              
|  Leonard   |  X  |  B  |                              
|   Penny    |  X  |  C  |                              
|   Howard   |  X  |  A  |                              
| Bernadette |  X  |  D  |                              
|  Sheldon   |     |  A  |                              
|    Raj     |     |  B  |                              
|    Amy     |     |     |                              
+------------+-----+-----+                             

Upvotes: 1

Related Questions