pythonbeautifulsoupprettytable

Merging Two Tables with pretty table


After scrapping with beautiful soup, I have 2 tables :

x = PrettyTable()
x.field_names = ['Titre', 'Price']
y = PrettyTable()
y.field_names = ['Description']

OUTPUT:

x = 
+-----------------+ 
| Titre | Price   |       
+-----------------+
| a     |  abc    | 
| b     |  xyz    |
+-----------------


y = 
+-----------------+ 
|   DESCRIPTION   |       
+-----------------+
|       abc       | 
|       xyz       |
+-----------------

Desired Output:

+-----------------+-----------------+ 
| Titre | Price   |  DESCRIPTION    |        
+-----------------+-----------------+
| a     |  abc    |       abc       |
| b     |  xyz    |       xyz       |
+-----------------+-----------------+

Is it possible to merge them ?

To have something like :

z = PrettyTable()
z.field_names = ['Titre', 'Price','Description']

Solution

  • Possible solution in case of number of rows in "y" should be less or equal to number of rows in "x". Or you can just switch the "x" "y".

    z = PrettyTable()
    z_rows = []
    counter = 0
    for i in x.rows:
        i.extend(y.rows[counter])
        counter += 1
        z_rows.append(i)
    
    field = []
    field.extend(x.field_names)
    field.extend(y.field_names)
    
    z.field_names = field
    z.add_rows(z_rows)
    

    Result would look like this:

    enter image description here