I have a dictionary:
import math
import random
d = {1: ["Spices", math.floor(random.gauss(40, 5))],
2: ["Other stuff", math.floor(ran
Based on Le Droid's code, I added separator '-' for each row which could make the print more clear. Thanks, Le Droid.
def printTable(myDict, colList=None):
if not colList:
colList = list(myDict[0].keys() if myDict else [])
myList = [colList] # 1st row = header
for item in myDict:
myList.append([str(item[col] or '') for col in colList])
#maximun size of the col for each element
colSize = [max(map(len,col)) for col in zip(*myList)]
#insert seperating line before every line, and extra one for ending.
for i in range(0, len(myList)+1)[::-1]:
myList.insert(i, ['-' * i for i in colSize])
#two format for each content line and each seperating line
formatStr = ' | '.join(["{{:<{}}}".format(i) for i in colSize])
formatSep = '-+-'.join(["{{:<{}}}".format(i) for i in colSize])
for item in myList:
if item[0][0] == '-':
print(formatSep.format(*item))
else:
print(formatStr.format(*item))
Output:
-----------+----------+---------------
a | bigtitle | c
-----------+----------+---------------
123 | 456 | 789
-----------+----------+---------------
x | y | z
-----------+----------+---------------
2016-11-02 | 1.2 | 78912313213123
-----------+----------+---------------