如何优雅地格式化字典字符串输出

72 投票
4 回答
68537 浏览
提问于 2025-04-16 04:16

我想知道有没有简单的方法来格式化字典输出的字符串,比如这样:

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

..., 直接用 str(dict) 转换的话,结果会非常难以阅读 ...

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

根据我对 Python 的了解,我可能需要写很多代码,还要处理很多特殊情况和使用 string.replace(),但这个问题看起来并不复杂,不应该需要写一千行代码。

请推荐一种最简单的方法来按照这种格式格式化任何字典。

4 个回答

7
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',
  },
}

注意,我在这里假设所有的键都是字符串,或者至少是一些比较好看的对象。

43

使用 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 的格式,你就能得到想要的结果。

119

根据你想用输出做什么,有一种选择是用JSON格式来显示。

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处理的。如果字典里包含了不能被JSON序列化的东西,比如类或者函数,就需要写一些额外的代码来处理了。

撰写回答