Paul
Paul

Reputation: 5974

Print out dictionary in a table format?

I have a dictionary that looks like:

band2 = {'channel11': [10812, 2162, 1972, 0], 'channel10': [10787, 2157, 1967, 0], 'channel3': [10612, 2122, 1932, 0], 'channel2': [10589, 2117, 1927, 0], 'channel1': [10564, 2112, 1922, 20], 'channel7': [10712, 2142, 1952, 26], 'channel6': [10687, 2137, 1947, 0], 'channel5': [10662, 2132, 1942, 32], 'channel4': [10637, 2127, 1937, 26], 'channel9': [10762, 2152, 1962, 0], 'channel8': [10737, 2147, 1957, 0], 'channel12': [10837, 2167, 1977, 15]}

I then sort it like so:

zipped = zip(*((key, value) for key, value in sorted(band2.items(), 
                                             key= lambda x: int(x[0][7:]))))

This gives this result:

[('channel1', 'channel2', 'channel3', 'channel4', 'channel5', 'channel6', 'channel7', 'channel8', 'channel9', 'channel10', 'channel11', 'channel12'), ([10564, 2112, 1922, 20], [10589, 2117, 1927, 0], [10612, 2122, 1932, 0], [10637, 2127, 1937, 26], [10662, 2132, 1942, 32], [10687, 2137, 1947, 0], [10712, 2142, 1952, 26], [10737, 2147, 1957, 0], [10762, 2152, 1962, 0], [10787, 2157, 1967, 0], [10812, 2162, 1972, 0], [10837, 2167, 1977, 15])]

I am wondering how do i print this out in a certain format:

Channel 1 Channel 2 ...... Channel 12
value[0] value[0] ........value[0]
value[1]/value[2] value[1]/value[2].....value[1]/value[2]
value[3] value[3]...........value[3]

So an example output would be:

Channel 1 Channel 2  <other values> Channel 12
10564     10589      <other values>    10837
2112/1922 2117/1927  <other values>    2167/1977
20        0          <other values>    15

I'm unsure how to go about printing this in a neat table, would I use format?

Upvotes: 1

Views: 3268

Answers (2)

interestinglythere
interestinglythere

Reputation: 1253

I ended up not using zipped.

table = [[], [], [], []]
# We can't just sort the channel names because 'channel11' < 'channel2'
channel_numbers = []
for channel_name in band2.keys():
    if channel_name.startswith('channel'):
        channel_number = int(channel_name[7:])
        channel_numbers.append(channel_number)
    else:
        raise ValueError("channel name doesn't follow pattern")
channel_numbers.sort()

for channel_number in channel_numbers:
    channel_data = band2['channel%d' % channel_number]
    table[0].append('Channel %d' % channel_number)
    table[1].append(str(channel_data[0]))
    table[2].append('%s/%s' % (channel_data[1], channel_data[2]))
    table[3].append(str(channel_data[3]))

for line in table:
    print('\t'.join(line))

If tabs don't work well, determine the width of each column and pad with spaces:

for channel_number in channel_numbers:
    channel_data = band2['channel%d' % channel_number]
    column = [
        'Channel %d' % channel_number,
        str(channel_data[0]),
        '%s/%s' % (channel_data[1], channel_data[2]),
        str(channel_data[3])
    ]
    cell_widths = map(len, column)
    column_width = max(cell_widths)
    for i in range(len(column)):
        cell = column[i]
        padded_cell = cell + ' '*(column_width-len(cell))
        table[i].append(padded_cell)

for line in table:
    # If tabs don't make the columns align properly, try iterating through
    # column in line, and padding it with the appropriate number of spaces.
    print(' '.join(line))

Upvotes: 2

waitingkuo
waitingkuo

Reputation: 93754

You can try pandas which provide a nice structure to deal with table:

Pandas's DataFrame can be built from items:

In [69]: import pandas as pd
In [70]: df = pd.DataFrame.from_items(sorted(band2.items(), key=lambda x: int(x[0][7:])))
In [71]: df = df.astype('string')

Concat row 1 and row 2

In [72]: df.ix[1] = df.ix[1] + '/' + df.ix[2]
In [73]: df = df.ix[[0, 1, 3]] 

Print it without index

In [74]: print df.to_string(index=None)

  channel1   channel2   channel3   channel4   channel5   channel6   channel7   channel8   channel9  channel10  channel11  channel12
     10564      10589      10612      10637      10662      10687      10712      10737      10762      10787      10812      10837
 2112/1922  2117/1927  2122/1932  2127/1937  2132/1942  2137/1947  2142/1952  2147/1957  2152/1962  2157/1967  2162/1972  2167/1977
        20          0          0         26         32          0         26          0          0          0          0         15  

Upvotes: 3

Related Questions