How to Format dict string outputs nicely

后端 未结 3 496
不知归路
不知归路 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:34

    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.

    0 讨论(0)
  • 2020-12-23 09:37
    def format(d, tab=0):
        s = ['{\n']
        for k,v in d.items():
            if isinstance(v, dict):
                v = format(v, tab+1)
            else:
                v = repr(v)
    
            s.append('%s%r: %s,\n' % ('  '*tab, k, v))
        s.append('%s}' % ('  '*tab))
        return ''.join(s)
    
    print format({'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}})
    

    Output:

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

    Note that I'm sorta assuming all keys are strings, or at least pretty objects here

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题