我需要显示以下词典:
{'ch1':'New1'}
{'Show1':'one','Show2':'two','Show3':'three'}
{'ch2':'New2'}
{'Show4':'four','Show5':'five'}
输出如下例:
New1 New2
one four
two five
three
答案 0 :(得分:1)
非结构化数据(没有用于选择键的好系统,四个词典而不是一个词典),因此输出它们的代码也将是非结构化的:
title1 = {'ch1':'New1'}
data1 = {'Show1':'one','Show2':'two','Show3':'three'}
title2 = {'ch2':'New2'}
data2 = {'Show4':'four','Show5':'five'}
title = "{:8s}{:10s}".format(title1['ch1'], title2['ch2'])
row1 = "{:8s}{:10s}".format(data1 ['Show1'], data2 ['Show4'])
row2 = "{:8s}{:10s}".format(data1 ['Show2'], data2 ['Show5'])
row3 = "{:8s}{:10s}".format(data1 ['Show3'], "" )
print(title)
print(row1)
print(row2)
print(row3)
它给出了这个输出:
New1 New2
one four
two five
three
如你所愿。
施工为
"{:8s}{:10s}".format(title1['ch1'], title2['ch2'])
表示您分别为8
函数中的参数保留10
和format()
个职位。所以他们将从每一行的相同位置开始。
你觉得它不是很好吗?
答案 1 :(得分:0)
鉴于您希望一次打印一行,并且元素来自两个列表,您希望使用zip函数,该函数为您提供每个列表中包含一个元素的对列表。
for line in zip(['a1', 'a2', 'a3'], ['b1', 'b2', 'b3']):
print(line)
打印
('a1', 'b1')
('a2', 'b2')
('a3', 'b3')
但是,在您的情况下,列表具有不同的长度,因此通常的zip不起作用:
for line in zip(['a1', 'a2', 'a3'], ['b1', 'b2']):
print(line)
打印
('a1', 'b1')
('a2', 'b2')
在这种情况下,您可以使用itertools.zip_longest构建所需的对:
from itertools import zip_longest
for line in zip_longest(['a1', 'a2', 'a3'], ['b1', 'b2'], fillvalue=''):
print(line)
打印
('a1', 'b1')
('a2', 'b2')
('a3', '')
总之,对于这个问题,你要求完整的解决方案是
from itertools import zip_longest
a_head = {'ch1':'New1'}
a_data = {'Show1':'one','Show2':'two','Show3':'three'}
b_head = {'ch2':'New2'}
b_data = {'Show4':'four','Show5':'five'}
# extract the values in the rigt order (sorted by the keys in the dictionary)
a_list = [a_data[key] for key in sorted(a_data.keys())]
b_list = [b_data[key] for key in sorted(b_data.keys())]
# pack the header in a single line
header = ['{:8}{:8}'.format(a, b) for a, b in zip_longest(a_head.values(), b_head.values(), fillvalue='')]
# pack the data in a single line
lines = ['{:8}{:8}'.format(a, b) for a, b in zip_longest(a_list, b_list, fillvalue='')]
# print everything
for line in header:
print(line)
for line in lines:
print(line)