代码之家  ›  专栏  ›  技术社区  ›  erikbstack

如何很好地格式化dict字符串输出

  •  50
  • erikbstack  · 技术社区  · 15 年前

    我想知道是否有一种简单的方法来格式化dict输出的字符串,例如:

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

    …,一个简单的str(dict)只会给你一个相当不可读的。。。

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

    就我对Python的了解而言,我必须编写大量带有许多特殊情况的代码字符串.替换()调用,这个问题本身看起来不像1000行问题。

    3 回复  |  直到 8 年前
        1
  •  104
  •   David Narayan    15 年前

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

    输出:

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

    这种方法需要注意的是,有些东西不能通过JSON序列化。如果dict包含类或函数之类的不可序列化项,则需要一些额外的代码。

        2
  •  40
  •   pyfunc    15 年前

    使用pprint

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

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

    玩转pprint格式,你可以得到想要的结果。

        3
  •  6
  •   Knio    15 年前
    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'}})
    

    输出:

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