質問

Let's say I have a dictionary like:

my_dict = {1:[1,2,3],4:[5,6,7],8:[9,10,11]}

I want to be able to print it so it looks like:

1 4 8
1 5 9
2 6 10
3 7 11

I'm actually working with much larger dictionaries and it would be nice if I can see how they look since they're so hard to read when I just say print(my_dict)

役に立ちましたか?

解決

You could use zip() to create columns:

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

Demo:

>>> 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

This does assume that the value lists are all of equal length; if not the shortest row will determine the maximum number of rows printed. Use itertools.zip_longest() to print more:

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

Demo:

>>> 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

You may want to use sep='\t' to align the columns along tab stops.

他のヒント

>>> 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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top