Dan*_*ook 0 python formatting dictionary pretty-print
假设我有一个字典:
my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}
Run Code Online (Sandbox Code Playgroud)
我想能够打印它看起来像:
1 4 8
1 5 9
2 6 10
3 7 11
Run Code Online (Sandbox Code Playgroud)
我实际上正在处理更大的字典,如果我能看到它们的外观会很好,因为我只是说它们很难阅读 print(my_dict)
您可以zip()用来创建列:
for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
print(*row)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}
>>> for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
... print(*row)
...
1 4 8
1 5 9
2 6 10
3 7 11
Run Code Online (Sandbox Code Playgroud)
这确实假设值列表的长度相等; 如果不是,最短的行将确定打印的最大行数.使用itertools.zip_longest()打印更多:
from itertools import zip_longest
for row in zip_longest(*([key] + value for key, value in sorted(my_dict.items())), fillvalue=' '):
print(*row)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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
Run Code Online (Sandbox Code Playgroud)
您可能希望使用sep='\t'沿制表位对齐列.