PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to print a python list-of-lists compactly, but still readably?

 July 23, 2022     json, python     No comments   

Issue

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?


Solution

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


Answered By - Grismar
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing