首页 > 编程语言 > 详细

Python 格式化打印 dict、json 数据

时间:2020-04-12 12:16:43      阅读:69      评论:0      收藏:0      [点我收藏+]

1.使用官方模块 pprint 格式化打印 dict 数据

import pprint
# indent:定义几个空格的缩进
pp = pprint.PrettyPrinter(indent=2)
info = dict(age=50, money=0, a=1, b=dict(h=7, i=8, j=9), c=2, d=3, e=4, f=5, g=6)
pp.pprint(info)

输出:

{ ‘a‘: 1,
  ‘age‘: 50,
  ‘b‘: {‘h‘: 7, ‘i‘: 8, ‘j‘: 9},
  ‘c‘: 2,
  ‘d‘: 3,
  ‘e‘: 4,
  ‘f‘: 5,
  ‘g‘: 6,
  ‘money‘: 0}

 

2.格式化打印 json 格式的数据

import json
info = dict(age=50, money=0, a=1, b=dict(h=7, i=8, j=9), c=2, d=3, e=4, f=5, g=6)
# indent:定义几个空格的缩进
# separators:定义 "," ":" 前后的空格数量
print(json.dumps(info, indent=1, separators=(‘, ‘, ‘: ‘), ensure_ascii=False))

输出:

{
 "age": 50, 
 "money": 0, 
 "a": 1, 
 "b": {
  "h": 7, 
  "i": 8, 
  "j": 9
 }, 
 "c": 2, 
 "d": 3, 
 "e": 4, 
 "f": 5, 
 "g": 6
}

 

Python 格式化打印 dict、json 数据

原文:https://www.cnblogs.com/lowmanisbusy/p/12683897.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!