在Python中,如何将不同字典中相同键的所有值垂直打印?

-1 投票
1 回答
1206 浏览
提问于 2025-04-30 13:27

假设我想输出三行内容,每一行对应一个不同的表格。每一列的内容是与键对应的值。

这样打印出来的结果会是竖着的:

for i in list_of_keys:
    print dict1[i], dict2[i], dict3[i]

有没有什么简单的方法可以让字典的值一个接一个地叠在一起,而不是竖着排列呢?

一种方法是这样写:

for i in list_of_keys:
    print dict1[i],
for i in list_of_keys:
    print dict2[i],

但这里的问题是,如果字典里的值比一行能放下的还多,就会出现多行的情况,直到这个字典的值用完,然后下面又会出现多行。这样就不能把字典的值和键对齐,导致列的排列不整齐。

暂无标签

1 个回答

0

假设你在用Python 2,我写了一个叫做 pprint_multiline 的函数,你可以根据自己的需要进行各种自定义。

你可以自定义以下内容:

  • 每行的长度
  • 项目之间的分隔符
  • 行与行之间的分隔符(如果想要两块行之间留空行,可以用空字符串;如果不想要任何分隔符,可以用 None
  • 每个项目的对齐方式
  • 对齐时使用的字符。

这个函数接受一个列表的列表,目的是将它们横向打印出来。所以在调用这个函数之前,你需要把字典里的内容拆开,就像我下面给的例子那样。

这个函数适用于字典中的任何值,只要这些值实现了 __str__ 函数(大多数Python对象都有这个功能)。

函数的代码如下:

def pprint_multilines(linelen=80, separator=' ', line_separator=None,
                      align='left', align_char=' ', lists=[]):
    maxlen = max(len(lst) for lst in lists)
    printed_lines = ['']*len(lists)
    empty = True
    printed = False
    for i in xrange(maxlen):
        max_item_len = max(len(str(lst[i])) for lst in lists)
        if max_item_len + len(printed_lines[0]) + 1 > linelen:
            if printed and line_separator is not None:
                if len(line_separator) > 0:
                    print line_separator*(linelen/len(line_separator))
                else:
                    print
            for printed_line in printed_lines:
                print printed_line
            printed = True
            printed_lines = ['']*len(lists)
            empty = True
        for lst_idx, lst in enumerate(lists):
            if not empty:
                printed_lines[lst_idx] += separator
            if align == 'left':
                printed_lines[lst_idx] += str(lst[i]).ljust(max_item_len, align_char)
            else: # align == 'right'
                printed_lines[lst_idx] += str(lst[i]).rjust(max_item_len, align_char)
        else:
            empty = False
    if not empty:
        if printed and line_separator is not None:
            if len(line_separator) > 0:
                print line_separator*(linelen/len(line_separator))
            else:
                print
        for printed_line in printed_lines:
            print printed_line

想看看它是怎么工作的,你可以参考以下例子:

dict1 = {'a': 'first', 'b': 'second', 'c': 3, 'd': ['the', 'fourth']}
dict2 = {'a': 1, 'b':2, 'c':3, 'd':4}
dict3 = {'a': '1', 'b':'two', 'c':'three', 'd': 'fourth'}
list_of_keys = ['a','b','c','d']

pprint_multilines(linelen=15, separator=' ', align='left', align_char=' ',
                  line_separator='-',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=15, separator=' ', align='left', align_char=' ',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=25, separator=' ', align='left', align_char=' ',
                  line_separator='',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=45, separator=' ', align='left', align_char='_',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=45, separator=' ', align='right', align_char=' ',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])

这些例子会输出(附带一些注释):

first second
1     2
1     two
---------------   <-- This is the line separator
3                 <-- This next item fits in 15 chars, but
3                     if appended to the previous line
three                 this item won't fit, so break the third item to new lines
---------------   <-- Note that this spans the specified line length
['the', 'fourth']
4
fourth

first second
1     2
1     two
3                 <-- No line separator!
3
three
['the', 'fourth']
4
fourth

first second 3     <-- linelen=25, the third item now fits!
1     2      3
1     two    three
                   <-- A blank line separator
['the', 'fourth']
4
fourth

first second 3____ ['the', 'fourth'] <-- Showing alignment chars
1____ 2_____ 3____ 4________________ <-- linelen=45, everything fits!
1____ two___ three fourth___________

first second     3 ['the', 'fourth'] <-- These blocks are right-aligned
    1      2     3                 4
    1    two three            fourth

撰写回答