How to Format dict string outputs nicely

后端 未结 3 521
不知归路
不知归路 2020-12-23 09:15

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

{
  \'planet\' : {
    \'name\' : \'Earth\',
    \'has\' : {
      \'plants\         


        
3条回答
  •  被撕碎了的回忆
    2020-12-23 09:42

    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

提交回复
热议问题