0

I have a class Table with a tuple called header

self.header = ("Column_1", "Column_2", "Column_3", "Column_4", "Column_5")

and a dictionary of tuples called __entries that are added with the function:

"""@brief Creates a new entry"""
def addEntry(self, column_1 : str , column_2 : str, column_3 : bool, column_4 : List[str], column_5 : Callable[[],None]) -> None:
    self.__entries[column_1] = (column_1, column_2, column_3, column_4, column_5)

I want to print the header and all entries as a formatted table. My current attempt is:

"""@brief Print the header and all entries as a table"""
def print(self) -> None:
    print("|\t" + self.header[0] + "\t|\t" + self.header[1] + "\t|\t" + self.header[2] + "\t|\t" + self.header[3]+ "\t|" + self.header[4]+ "\t|")
    for key in self.__entries:
        entry = self.__entries[key]
        print("|\t" + entry[0] + "\t|\t" + entry[1] + "\t|\t" + str(entry[2]) + "\t|\t" + str(entry[3]) + "\t|\t" + str(entry[4])+ "\t|")

But obviously this doesn't resize the columns, and so the program:

def Foo() -> None:
    print(HelloWorld)

def Bar() -> None:
    print(HelloWorld)

def Baz() -> None:
    print(HelloWorld)

if __name__== "__main__":
    table = Table()
    table.addEntry("test","Craig",False,[], Foo)
    table.addEntry("test2","Bob",False,[], Bar)
    table.addEntry("test3","Bill",False,[], Baz)

    methodRegistry.print()

Outputs:

|       Column_1        |       Column_2        |       Column_3        |       Column_4        | Column_5      |
|       test    |       Craig   |       False   |       []      |       <function Foo at 0x7f1192b56e18>        |
|       test2   |       Bob     |       False   |       []      |       <function Bar at 0x7f1191464730>        |
|       test3   |       Bill    |       False   |       []      |       <function Baz at 0x7f11914647b8>        |

I am new to python, but I imagine there is an easy way to do this without manually having to calculate the width of each row and adjust accordingly.

Full source code can be found here: https://gitlab.com/snippets/1936949

0

2 Answers 2

2

I highly suggest you to convert your Table into a pandas Dataframe. If you do so, obtaining a tabular representation of your table is easy using to_markdown:

# Generating a test table in pandas
df  = pd.DataFrame({'Column_2': {'test': 'Craig', 'test2': 'Bob', 'test3': 'Bill'},
 'Column_3': {'test': False, 'test2': False, 'test3': False},
 'Column_4': {'test': '[]', 'test2': '[]', 'test3': '[]'},
 'Column_5': {'test': '<function Foo at 0x7f9f898a0e18>',
  'test2': '<function Bar at 0x7f9f881ae730>',
  'test3': '<function Baz at 0x7f9f881ae7b8>'}})
df.index.name = 'Column_1'

# Printing the table in a nice tabular way:
print(df.to_markdown())
| Column_1   | Column_2    | Column_3    | Column_4    | Column_5                         |
|:-----------|:------------|:------------|:------------|:---------------------------------|
| test       | Craig       | False       | []          | <function Foo at 0x7f9f898a0e18> |
| test2      | Bob         | False       | []          | <function Bar at 0x7f9f881ae730> |
| test3      | Bill        | False       | []          | <function Baz at 0x7f9f881ae7b8> |

In general, all table operations are supported by pandas, which is why it is not recommended to build your own Table structure (unless this is part of some learning course).

Sign up to request clarification or add additional context in comments.

2 Comments

I wanted to create a table data structure that used type hints from the typing package. The table in the question had generic headers (Collumn_1 etc...), but my actual code had more specific meanings and the data in the table was a specific type. E.g one column was a User class. But as I said earlier, I am very new to python and am probably trying to do this in a c++ way. Maybe the lesson learnt here is I should use premade packages instead of making my own.
that is indeed my recommendation! No need to reinvent the wheel. Have a look at pandas and try to solve your requirements with it
2

Use a well-known Python package to print in tabular format. For example, you may use prettytable. You can install it with the command: pip install prettytable.

>>> from prettytable import PrettyTable
>>> t = PrettyTable(hdrs)
>>>
>>> headers = ("Column_1", "Column_2", "Column_3", "Column_4", "Column_5")
>>> t = PrettyTable(headers)
>>> t.add_row(("test","Craig",False,[], 'Foo'))
>>> t.add_row(("test2","Bob",False,[], 'Bar'))
>>> t.add_row(("test3","Bill",False,[], 'Baz'))
>>> print(t)
+-----------+-----------+-----------+-----------+-----------+
| Column_1  | Column_2  | Column_3  | Column_4  | Column_5  |
+-----------+-----------+-----------+-----------+-----------+
|    test   |   Craig   |   False   |     []    |    Foo    |
|   test2   |    Bob    |   False   |     []    |    Bar    |
|   test3   |    Bill   |   False   |     []    |    Baz    |
+-----------+-----------+-----------+-----------+-----------+

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.