What is the Most Efficient Way of Printing A Dict's Contents Out In Columns?

Terry Reedy tjreedy at udel.edu
Tue Jun 14 12:06:18 EDT 2011


On 6/14/2011 11:29 AM, Zachary Dziura wrote:
> I have a dict that I would like to print out in a series of columns,
> rather than as a bunch of lines. Normally when you do print(dict), the
> output will look something like this:
>
> {'Header2': ['2', '5', '8'], 'Header3': ['3', '6', '9'], 'Header1':
> ['1', '4', '7'], 'Header4': ['10', '11', '12']}
>
> I can then iterate through (in this case) a list of the headers in
> order to produce something similar to this:
>
> Header1 = ['1', '4', '7']
> Header2 = ['2', '5', '8']
> Header3 = ['3', '6', '9']
> Header4 = ['10', '11', '12']
>
> What I want to know is how I can print out that information in a
> column, where the header is the first line of the column, with the
> data following underneath, like so:
>
> Header1        Header2        Header3        Header4
> 1                  2                  3                   4
> 5                  6                  7                   8
> 9                  10                11                 12

You did not specify how much can be assumed about the dict and built in 
to the program and how much needs to be discovered with code. Assuming 
that this is not homework, here is a start:

d={'Header2': ['2', '5', '8'], 'Header3': ['3', '6', '9'],
    'Header1': ['1', '4', '7'], 'Header4': ['10', '11', '12']}

arr = []
for key,value in d.items():
     line = ['{:>10s}'.format(key)]
     for num in value:
         line.append('{:>10s}'.format(num))
     arr.append(line)

for line in zip(*arr):
     for item in line:
         print(item, end='')
     print() # newline
 >>>
    Header2   Header3   Header1   Header4
          2         3         1        10
          5         6         4        11
          8         9         7        12

For zip(*arr) to work properly, each line of arr should have the same 
length, which means that either each value of d has the same length or 
that you find the max length and pad lines with blanks up to the max 
length. The code above assumes the first.

If the items in each value of d are not strings, more fiddling is 
needed. The printed field size is also arbitrary. It needs adjusting for 
the actual max length. You might want to adjust it for each key-value 
pair in the dict, which is to say, each column of the resulting table.

-- 
Terry Jan Reedy




More information about the Python-list mailing list