Home > Blockchain >  How to print a python list-of-lists compactly, but still readably?
How to print a python list-of-lists compactly, but still readably?

Time:07-18

Is there a way to control how json is formatted using json.dumps? The default puts one value on each line, which for a very simple list becomes unreadably spread out.

For example:

import json
x = [[1,1,1,1,1] for _ in range(5)] 
print("A", json.dumps(x, indent=2))
print("B", json.dumps(x))

gives:

A [
  [
    1,
    1,
    1,
    1,
    1
  ],
  [
    1,
    and so on...

and:

B [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

A is too spread out, and B is too dense to read. Of course both of these look fine because they're toy examples, but given real data, this gets tricky. It'd be really nice to get

[
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1]
]

This feels like a pretty trivial bit of code to write myself, but it'd be nice to be able to pass an option to json.dumps and not need to worry.

Basic implementation:

def print_rectangularish_list(the_list, indent=2):
    print("[")
    for sub_list in the_list:
        if len(str(sub_list)) < 80:
            print(f"{' ' * indent}{sub_list},")
        else:
            print(json.dumps(sub_list, indent=indent))
    print("]")

x = [[1, 1, 1, 1, 1] for _ in range(5)]
print_rectangularish_list(x, indent=2)
x.append([1 for _ in range(45)])
print_rectangularish_list(x, indent=2)

This is nowhere near perfect, but it illustrates what I'd like to be able to do with json.dumps or even another module.

I think that perhaps a target_line_length or a compact kwarg would be nice?

Does anyone have any suggestions?

CodePudding user response:

If you try pprint.pprint():

from pprint import pprint

x = [[1,1,1,1,1] for _ in range(5)]
pprint(x)

Output:

[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]
  • Related