Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Format dict string outputs nicely

I wonder if there is an easy way to format Strings of dict-outputs such as this:

{   'planet' : {     'name' : 'Earth',     'has' : {       'plants' : 'yes',       'animals' : 'yes',       'cryptonite' : 'no'     }   } } 

..., where a simple str(dict) just would give you a quite unreadable ...

{'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}} 

For as much as I know about Python I would have to write a lot of code with many special cases and string.replace() calls, where this problem itself does not look so much like a 1000-lines-problem.

Please suggest the easiest way to format any dict according to this shape.

like image 868
erikbstack Avatar asked Sep 17 '10 07:09

erikbstack


People also ask

How do you print a dictionary in Python nicely?

Use pprint() to Pretty Print a Dictionary in Python Within the pprint module there is a function with the same name pprint() , which is the function used to pretty-print the given string or object. First, declare an array of dictionaries. Afterward, pretty print it using the function pprint. pprint() .

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

What method is used to format string output in Python?

Python can format an object as a string using three different built-in functions: str() repr() ascii()


2 Answers

Depending on what you're doing with the output, one option is to use JSON for the display.

import json x = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}  print json.dumps(x, indent=2) 

Output:

{   "planet": {     "has": {       "plants": "yes",        "animals": "yes",        "cryptonite": "no"     },      "name": "Earth"   } } 

The caveat to this approach is that some things are not serializable by JSON. Some extra code would be required if the dict contained non-serializable items like classes or functions.

like image 176
David Narayan Avatar answered Sep 28 '22 04:09

David Narayan


Use pprint

import pprint  x  = {   'planet' : {     'name' : 'Earth',     'has' : {       'plants' : 'yes',       'animals' : 'yes',       'cryptonite' : 'no'     }   } } pp = pprint.PrettyPrinter(indent=4) pp.pprint(x) 

This outputs

{   'planet': {   'has': {   'animals': 'yes',                              'cryptonite': 'no',                              'plants': 'yes'},                   'name': 'Earth'}} 

Play around with pprint formatting and you can get the desired result.

  • http://docs.python.org/library/pprint.html
like image 42
pyfunc Avatar answered Sep 28 '22 05:09

pyfunc