vpd vpd - 1 year ago 62
Python Question

Formatting a dictionary in table format

I need to show my dictionary in table format:

res = OrderedDict([('Release', '3.7.3'), ('REFDB', ['1234', '4567', '4567']), ('URL', ['http://www.test.com', 'http://www.foo.com', 'http://www.bar.com'])])

I am able to print the values in list format with this code

if res:
for key, val in res.items():
print (key, '-''\n', val)
print ('Version not found')

My expected format is -

3.7.3 12345 http://google.com
232323 http://www.yahoo.com
4343454 http://www.test.com
5454554 http://www.bar.com

Answer Source

Here's one way to do it with zip and zip_longest:

from collections import OrderedDict
from itertools import zip_longest

d = OrderedDict([('Release', '3.7.3'), ('REFDB', ['1234', '4567', '4567']), ('URL', ['http://www.test.com', 'http://www.foo.com', 'http://www.bar.com'])])

f = lambda x: x if isinstance(x, list) else [x]

for tup in zip(*d.items()):
    for a, b, c in zip_longest(*map(f, tup), fillvalue=''):
        print('{:15}{:15}{:15}'.format(a, b, c))

Release        REFDB          URL            
3.7.3          1234           http://www.test.com
               4567           http://www.foo.com
               4567           http://www.bar.com

You can change the intercolumn spacing in the string formatting if you wish to have or more less spacing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download