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

Karim karim.liateni at free.fr
Tue Jun 14 14:28:46 EDT 2011


On 06/14/2011 05:29 PM, 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
Over alternative that only costs 2 lines of code, use pretty print (not 
in columns but crystal clear):

import pprint
pprint.pprint(my_dict)

or in a file:
pprint.pprint(my_dict, open("output.dat", "wb"))

Cheers
karim





More information about the Python-list mailing list