Search code examples
pythontabulate

How to add vertival headers in tabulate?


So I made a table in tabulate and the output looks like this:

enter image description here

But I want it to look like this:

enter image description here

So how do I do that ?

this is my code:

from tabulate import tabulate

nums = {"Numbers": [0, 3.5, " ", -2, " "], "Seconds": [" ", " ", 24, " ", 3]}
print(
    tabulate(nums, tablefmt="grid", headers=nums.keys(), colalign=("center", "center"))
)

I will appreciate any help, thx.


Solution

  • Can you try with the following input:

    nums = [["Numbers", 0, 3.5, " ", -2, " "], ["Seconds", " ", " ", 24, " ", 3]]
    

    and by removing the headers=nums.keys() argument ?

    Edit: if your input is a dictionary as you shown, you can transform it into a list of lists as above:

    from tabulate import tabulate
    nums = {"Numbers": [0, 3.5, " ", -2, " "], "Seconds": [" ", " ", 24, " ", 3]}
    print(
        tabulate([[k]+nums[k] for k in nums], tablefmt="grid", colalign=("center", "center"))
    )