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

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

本文介绍了如何很好地格式化字典字符串输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

{
  '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行的问题. /p>

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

解决方案

根据您对输出所做的操作,一种选择是将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序列化.如果字典包含不可序列化的项(例如类或函数),则需要一些额外的代码.

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

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

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

{'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.

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

解决方案

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

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.

这篇关于如何很好地格式化字典字符串输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:16