以表格格式化字典

时间:2016-11-21 13:36:41

标签: python dictionary ordereddictionary

我需要以表格格式显示我的字典:

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

我可以使用此代码

以列表格式打印值
if res:
    for key, val in res.items():
        print (key, '-''\n', val)
else:
    print ('Version not found')

我的预期格式是 -

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

2 个答案:

答案 0 :(得分:3)

以下是使用zipzip_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

如果希望间距更小或更多,则可以更改字符串格式的列间间距。

答案 1 :(得分:1)

您可以使用pandas库将字典转换为数据框。

from collections import OrderedDict
import pandas as pd

d = OrderedDict([('Release', '3.7.3'), ('REFDB', '12345 \n 232323 \n 4343454 \n 5454554'), ('URL', 'http://google.com \n http://www.yahoo.com \n http://www.test.com \n http://www.bar.com')])

for key in d.keys():
    d[key] =  d[key].split('\n')

df = pd.DataFrame.from_dict(d, orient='index').transpose()

输出将是:

  Release      REFDB                     URL
0   3.7.3     12345       http://google.com 
1    None    232323    http://www.yahoo.com 
2    None   4343454     http://www.test.com 
3    None    5454554      http://www.bar.com