How to add vertival headers in tabulate?

2k views Asked by At

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.

2

There are 2 answers

2
Frodon On BEST ANSWER

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"))
)
0
Constantin On

To transform the dictionary in the

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

you can use:

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

col = len(nums["Numbers"])
rd = len(nums)
l = []
ln = []
for k, v in nums.items():
    l = l + [k]
    l = l + v
    ln = ln + [l]
    l = []

print(ln)