在python中,如何从不同的字典中打印相同键的所有值?

时间:2014-10-30 06:09:55

标签: python dictionary output

假设我想输出三行。每行对应一个不同的表。列是键的相应值。

这会使打印成垂直:

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 :(得分: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