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

eri*_*ork 57 python string formatting

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

{
  'planet' : {
    'name' : 'Earth',
    'has' : {
      'plants' : 'yes',
      'animals' : 'yes',
      'cryptonite' : 'no'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

......,一个简单的str(dict)会给你一个相当难以理解的......

{'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
Run Code Online (Sandbox Code Playgroud)

对于我所知道的Python,我将不得不编写许多代码,包括许多特殊情况和string.replace()调用,其中这个问题本身看起来不像1000行问题.

请根据此形状建议格式化任何字典的最简单方法.

Dav*_*yan 90

根据您对输出的处理方式,一个选项是使用JSON进行显示.

import json
x = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}

print json.dumps(x, indent=2)
Run Code Online (Sandbox Code Playgroud)

输出:

{
  "planet": {
    "has": {
      "plants": "yes", 
      "animals": "yes", 
      "cryptonite": "no"
    }, 
    "name": "Earth"
  }
}
Run Code Online (Sandbox Code Playgroud)

对这种方法的警告是,有些东西不能被JSON序列化.如果dict包含类或函数之类的非可序列化项,则需要一些额外的代码.

  • 如果其中一个值是Date对象,则它不起作用 (3认同)

pyf*_*unc 37

使用pprint

import pprint

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

这输出

{   'planet': {   'has': {   'animals': 'yes',
                             'cryptonite': 'no',
                             'plants': 'yes'},
                  'name': 'Earth'}}
Run Code Online (Sandbox Code Playgroud)

使用pprint格式化,您可以获得所需的结果.


Kni*_*nio 6

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'}})
Run Code Online (Sandbox Code Playgroud)

输出:

{
'planet': {
  'has': {
    'plants': 'yes',
    'animals': 'yes',
    'cryptonite': 'no',
    },
  'name': 'Earth',
  },
}
Run Code Online (Sandbox Code Playgroud)

请注意,我假设所有键都是字符串,或者至少是漂亮的对象