Create table from dictionary python

I was looking for a solution with unknown columns width to print a database table. So here it is:

Show
    def printTable(myDict, colList=None):
       """ Pretty print a list of dictionaries (myDict) as a dynamically sized table.
       If column names (colList) aren't specified, they will show in random order.
       Author: Thierry Husson - Use it as you want but don't blame me.
       """
       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] if item[col] is not None else '') for col in colList])
       colSize = [max(map(len,col)) for col in zip(*myList)]
       formatStr = ' | '.join(["{{:<{}}}".format(i) for i in colSize])
       myList.insert(1, ['-' * i for i in colSize]) # Seperating line
       for item in myList: print(formatStr.format(*item))
    

    Sample:

    printTable([{'a':123,'bigtitle':456,'c':789},{'a':'x','bigtitle':'y','c':'z'}, \
        {'a':'2016-11-02','bigtitle':1.2,'c':78912313213123}], ['a','bigtitle','c'])
    

    Output:

    a          | bigtitle | c             
    ---------- | -------- | --------------
    123        | 456      | 789           
    x          | y        | z             
    2016-11-02 | 1.2      | 78912313213123
    

    In Psycopg context, you can use it this way:

    curPG.execute("SELECT field1, field2, ... fieldx FROM mytable")
    printTable(curPG.fetchall(), [c.name for c in curPG.description])
    

    If you need a variant for multi-lines rows, here it is:

    def printTable(myDict, colList=None, sep='\uFFFA'):
       """ Pretty print a list of dictionaries (myDict) as a dynamically sized table.
       If column names (colList) aren't specified, they will show in random order.
       sep: row separator. Ex: sep='\n' on Linux. Default: dummy to not split line.
       Author: Thierry Husson - Use it as you want but don't blame me.
       """
       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])
       colSize = [max(map(len,(sep.join(col)).split(sep))) for col in zip(*myList)]
       formatStr = ' | '.join(["{{:<{}}}".format(i) for i in colSize])
       line = formatStr.replace(' | ','-+-').format(*['-' * i for i in colSize])
       item=myList.pop(0); lineDone=False
       while myList or any(item):
          if all(not i for i in item):
             item=myList.pop(0)
             if line and (sep!='\uFFFA' or not lineDone): print(line); lineDone=True
          row = [i.split(sep,1) for i in item]
          print(formatStr.format(*[i[0] for i in row]))
          item = [i[1] if len(i)>1 else '' for i in row]
    

    Sample:

    sampleDict = [{'multi lines title': 12, 'bigtitle': 456, 'third column': '7 8 9'},
    {'multi lines title': 'w x y z', 'bigtitle': 'b1 b2', 'third column': 'z y x'},
    {'multi lines title': '2', 'bigtitle': 1.2, 'third column': 78912313213123}]
    
    printTable(sampleDict, sep=' ')
    

    Output:

    bigtitle | multi | third         
             | lines | column        
             | title |               
    ---------+-------+---------------
    456      | 12    | 7             
             |       | 8             
             |       | 9             
    ---------+-------+---------------
    b1       | w     | z             
    b2       | x     | y             
             | y     | x             
             | z     |               
    ---------+-------+---------------
    1.2      | 2     | 78912313213123
    

    Without sep parameter, printTable(sampleDict) gives you:

    bigtitle | multi lines title | third column  
    ---------+-------------------+---------------
    456      | 12                | 7 8 9         
    b1 b2    | w x y z           | z y x         
    1.2      | 2                 | 78912313213123
    

    View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a Dictionary. The task is to print the dictionary in table format.

    Examples:

    Input: 
    {1: ["Samuel", 21, 'Data Structures'], 
    2: ["Richie", 20, 'Machine Learning'], 
    3: ["Lauren", 21, 'OOPS with java'], 
    }
    Output: 
    NAME AGE COURSE 
    Samuel 21 Data Structures 
    Richie 20 Machine Learning 
    Lauren 21 OOPS with java 

    Method 1: Displaying results by iterating through values. 

    Python3

    dict1 = {}

    dict1 = {1: ["Samuel", 21, 'Data Structures'],

             2: ["Richie", 20, 'Machine Learning'],

             3: ["Lauren", 21, 'OOPS with java'],

             }

    print("{:<10} {:<10} {:<10}".format('NAME', 'AGE', 'COURSE'))

    for key, value in dict1.items():

        name, age, course = value

        print("{:<10} {:<10} {:<10}".format(name, age, course))

    Output

    NAME       AGE        COURSE    
    Samuel     21         Data Structures
    Richie     20         Machine Learning
    Lauren     21         OOPS with java
    

    Method 2: Displaying by using a matrix format 
     

    Python3

    dict1 = {}

    dict1 = {(0, 0): 'Samuel', (0, 1): 21, (0, 2): 'Data structures',

             (1, 0): 'Richie', (1, 1): 20, (1, 2): 'Machine Learning',

             (2, 0): 'Lauren', (2, 1): 21, (2, 2): 'OOPS with Java'

             }

    print(" NAME ", " AGE ", "  COURSE ")

    for i in range(3):

        for j in range(3):

            print(dict1[(i, j)], end='   ')

        print()

    Output

     NAME   AGE    COURSE 
    Samuel   21   Data structures   
    Richie   20   Machine Learning   
    Lauren   21   OOPS with Java   
    

    Method 3: Displaying by using zip format 

    Python3

    dict1 = {}

    dict1 = {'NAME': ['Samuel', 'Richie', 'Lauren'],

             'AGE': [21, 20, 21],

             'COURSE': ['Data Structures', 'Machine Learning', 'OOPS with Java']}

    for each_row in zip(*([i] + (j)

                          for i, j in dict1.items())):

        print(*each_row, " ")

    Output

    NAME AGE COURSE  
    Samuel 21 Data Structures  
    Richie 20 Machine Learning  
    Lauren 21 OOPS with Java