Formatting Lists into columns of a table output (python 3)

Jake Cannon picture Jake Cannon · Aug 19, 2016 · Viewed 45.3k times · Source

I have data that is collected in a loop and stored under separate lists that hold only the same datatypes (e.g. only strings, only floats) as shown below:

names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]

I have treated these lists as "columns" of a table and wish to print them out as a formatted table that should look something like this:

Names     | Weights | Costs | Unit_Costs  
----------|---------|-------|------------
bar       | 0.05    | 2.0   | 40.0
chocolate | 0.1     | 5.0   | 50.0
chips     | 0.25    | 3.0   | 12.0

I only know how to print out data from lists horizontally across table rows, I have looked online (and on this site) for some help regarding this issue, however I only managed to find help for getting it to work in python 2.7 and not 3.5.1 which is what I am using.
my question is:
how do I get entries from the above 4 lists to print out into a table as shown above.

Each item index from the lists above is associated (i.e. entry[0] from the 4 lists is associated with the same item; bar, 0.05, 2.0, 40.0).

Answer

Israel Unterman picture Israel Unterman · Aug 19, 2016

Here is a small implementation that does what you want in basic python (no special modules).


names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]


titles = ['names', 'weights', 'costs', 'unit_costs']
data = [titles] + list(zip(names, weights, costs, unit_costs))

for i, d in enumerate(data):
    line = '|'.join(str(x).ljust(12) for x in d)
    print(line)
    if i == 0:
        print('-' * len(line))

Output:


names       |weights     |costs       |unit_costs  
---------------------------------------------------
bar         |0.05        |2.0         |40.0        
chocolate   |0.1         |5.0         |50.0        
chips       |0.25        |3.0         |12.0