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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3733554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:28:47  来源:igfitidea点击:

How to Format dict string outputs nicely

pythonstringformatting

提问by erikbwork

I wonder if there is an easy way to format Strings of dict-outputs such as this:

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

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

..., where a simple str(dict) just would give you a quite unreadable ...

...,其中一个简单的 str(dict) 只会给你一个非常难以理解的 ...

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

For as much as I know about Python I would have to write a lot of code with many special cases and string.replace() calls, where this problem itself does not look so much like a 1000-lines-problem.

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

Please suggest the easiest way to format any dict according to this shape.

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

采纳答案by David Narayan

Depending on what you're doing with the output, one option is to use JSON for the display.

根据您对输出的处理方式,一种选择是使用 JSON 进行显示。

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.

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

回答by pyfunc

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.

玩转 pprint 格式,您可以获得所需的结果。

回答by Knio

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

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