Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a pretty printer for python data?

Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.

Is there something that will take any python object and display it in a more rational manner. e.g.

[0, 1,
    [a, b, c],
    2, 3, 4]

instead of:

[0, 1, [a, b, c], 2, 3, 4]

I know that's not a very good example, but I think you get the idea.

like image 841
Ferruccio Avatar asked Sep 18 '08 11:09

Ferruccio


People also ask

How do I print pretty data in Python?

Import pprint for use in your programs. Use pprint() in place of the regular print() Understand all the parameters you can use to customize your pretty-printed output. Get the formatted output as a string before printing it.

What is the name of Python's built in module for data pretty printer?

This article is about a pretty useful built-in module in Python, pprint. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way!


2 Answers

from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)

Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.

like image 169
Greg Hewgill Avatar answered Oct 20 '22 17:10

Greg Hewgill


Somtimes YAML can be good for this.

import yaml
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
print yaml.dump(a)

Produces:

- 0
- 1
- [a, b, c]
- 2
- 3
- 4
like image 31
rjmunro Avatar answered Oct 20 '22 18:10

rjmunro