Printing Dictionary in Vertical, and nested List in Horizontal

Viewed 246

How can I display the list (nested inside a dictionary) horizontally while still keeping the indentation? if I use print() only, the indentation is missing.

enter image description here

Tried below code, however the indentation is missing.

for key, value in new_pd_dict.items():
    print("%s: %s" % (key, value))

enter image description here

2 Answers

You can try to pass an argument to pprint, like compact=True. From the documentation, "if compact is true, as many items as will fit within the width will be formatted on each output line"

>>> pprint.pprint(new_pd_dict, compact=True)
{'Attack': [41, 87, 9, 38, 35, 30, 59, 98, 44, 9, 97, 53, 10, 79, 97, 46, 59,
            82, 75, 13, 72, 51, 80, 75, 80, 94, 88, 36, 76, 3, 32, 85, 95, 74,
            22, 28, 71, 57, 94, 29, 81, 89, 80, 42, 55, 7, 69, 3, 46, 40, 73,
            76, 41, 14, 47, 31, 45, 5, 78, 59, 4, 44, 4, 73, 9, 76, 60, 60, 16,
            2, 85, 6, 28, 21, 98, 1, 54, 24, 5, 1, 61, 39, 58, 26, 67, 52, 34,
            46, 23, 68, 25, 63, 36, 49, 66, 24, 2, 39, 15, 12]}

You can also adjust the width (defaults to 80) with width=<number> in function call.

There is no in-built python library that does this. But you can just do:

my_dict = {"x": [1, 2, 3],
           "y": [4, 5, 6],
           "z": [7, 8, 9]}

for key, value in my_dict.items():
    print("%s: %s" % (key, value))

This short piece of code will yield something like this in the console:

y: [4, 5, 6]
x: [1, 2, 3]
z: [7, 8, 9]
Related