【问题标题】:How to Format dict string outputs nicely如何很好地格式化dict字符串输出
【发布时间】:2011-04-13 14:38:53
【问题描述】:

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

{
  '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() 调用的代码,而这个问题本身看起来并不像 1000 行问题。

请建议根据此形状格式化任何 dict 的最简单方法。

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    根据您对输出的处理方式,一种选择是使用 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 序列化。如果 dict 包含类或函数等不可序列化的项目,则需要一些额外的代码。

    【讨论】:

    • 我想给你更多的答案。太棒了!谢谢,伙计!
    • 如果其中一个值是 Date 对象,则它不起作用
    • None 对象怎么样?它将被转换为null。您可以手动将这些 null 对象转换为 None
    • 我不认为这应该是一个可以接受的答案,因为虽然 json.dumps 序列化 dict,但并非所有 ptyhon 对象都是 json 可序列化的,并且生成的字符串缺乏正确的格式(截至撰写本文时)跨度>
    【解决方案2】:

    使用 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 格式,您可以获得所需的结果。

    【讨论】:

    • 嗯,它只有深度、宽度和缩进作为参数。我看不到让行星进入下一行的方法。当然,PP 结果的可读性更好,但是换行符+适当的空格对我来说是必要的。但是谢谢你给我看这个漂亮的包裹。在其他情况下非常方便。
    【解决方案3】:
    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',
      },
    }
    

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

    【讨论】:

    • 按预期工作。无论如何,我希望有人能找到一个包含所有电池的解决方案。如果周末之后没有其他事情,我会使用您的解决方案。感谢您的帮助!
    • 在自包含字典上陷入无限递归。
    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    相关资源
    最近更新 更多