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

Zach Dziura zcdziura at gmail.com
Tue Jun 14 13:48:34 EDT 2011


> 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

I just have one quick question. On the line where you have zip(*arr),
what is the * for? Is it like the pointer operator, such as with C? Or
is it exactly the pointer operator?

Otherwise, thank you for the example! This isn't homework, but I'm
working on something at work, and I was wondering how to properly
format the output from CSV files into another file. It's all a part of
an analyzer script for database tables, and the table wherein. Thank
you a bunch for the help!



More information about the Python-list mailing list