Search code examples
pythondictionaryformattingpretty-print

How can I print a dictionary in table format?


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)


Solution

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