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

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

问题描述

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

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

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

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

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

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

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.

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

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

推荐答案

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

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)

输出:

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

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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why does Python#39;s IDLE crash when I type a parenthesis on Mac?(为什么我在 Mac 上键入括号时 Python 的 IDLE 会崩溃?)
Tkinter crashes Jupyter kernel?(Tkinter 崩溃 Jupyter 内核?)
IDLE crash when opening on Mac OS X(在 Mac OS X 上打开时 IDLE 崩溃)
GVIM crashes when running python(运行 python 时 GVIM 崩溃)
PySide: Segfault(?) when using QItemSelectionModel with QListView(PySide:将 QItemSelectionModel 与 QListView 一起使用时的 Segfault(?))
Why does PyQt sometimes crash on exit?(为什么 PyQt 有时会在退出时崩溃?)