Python - Printing a dictionary as a horizontal table with headers

前端 未结 6 555
花落未央
花落未央 2020-12-02 19:01

I have a dictionary:

import math
import random

d = {1: ["Spices", math.floor(random.gauss(40, 5))],
    2: ["Other stuff", math.floor(ran         


        
6条回答
  •  失恋的感觉
    2020-12-02 19:25

    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
    -----------+----------+---------------
    

提交回复
热议问题