Python 如何以表格格式打印词典?

Python 如何以表格格式打印词典?,python,dictionary,formatting,pretty-print,Python,Dictionary,Formatting,Pretty Print,假设我有一本字典,比如: my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]} 我希望能够打印它,使其看起来像: 1 4 8 1 5 9 2 6 10 3 7 11 实际上,我正在使用更大的词典,如果我能看到它们的外观,那就太好了,因为当我说printmy_dict时,它们很难阅读。你可以使用zip创建列: for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):

假设我有一本字典,比如:

my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}
我希望能够打印它,使其看起来像:

1 4 8
1 5 9
2 6 10
3 7 11
实际上,我正在使用更大的词典,如果我能看到它们的外观,那就太好了,因为当我说printmy_dict时,它们很难阅读。你可以使用zip创建列:

for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
    print(*row)
演示:

这确实假设值列表的长度都相等;如果不是,最短的行将决定打印的最大行数。用于打印更多信息:

from itertools import zip_longest
for row in zip_longest(*([key] + value for key, value in sorted(my_dict.items())), fillvalue=' '):
    print(*row)
演示:


您可能希望使用sep='\t'沿制表位对齐列。

为什么不使用pprint模块进行漂亮的打印?我希望键作为标题,当字典变得很长时,我真的希望将其视为一个表。如果我没有弄错的话,这在python 2.7中不起作用?似乎不喜欢*行或zip_longest。@fantabolous:zip_longest在Python 2中被称为izip_longest。print*行在2中无法工作,除非您在模块中使用from _future _; import print u函数,或者使用print“”。joinrow。感谢Martijn进行python 2转换。我想我实际上也没有提到过@范塔博洛斯:嗯,看来我确实误读了你的评论。从我的评论中删除了这一点。
>>> my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}
>>> keys = my_dict.keys()
>>> print(*iter(keys), sep='\t')
8   1   4
>>> for v in zip(*(my_dict[k] for k in keys)): print(*v, sep='\t')
... 
9   1   5
10  2   6
11  3   7
>>> from itertools import zip_longest
>>> my_dict = {1:[1,2,3],4:[5,6,7,8],8:[9,10,11,38,99]}
>>> for row in zip_longest(*([key] + value for key, value in sorted(my_dict.items())), fillvalue=' '):
...     print(*row)
... 
1 4 8
1 5 9
2 6 10
3 7 11
  8 38
    99
>>> my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}
>>> keys = my_dict.keys()
>>> print(*iter(keys), sep='\t')
8   1   4
>>> for v in zip(*(my_dict[k] for k in keys)): print(*v, sep='\t')
... 
9   1   5
10  2   6
11  3   7