码迷,mamicode.com
首页 > 编程语言 > 详细

Python 格式化打印 dict、json 数据

时间:2020-04-12 10:55:34      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:info   打印   import   asc   格式化打印   ensure   int   inf   printer   

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 数据

标签:info   打印   import   asc   格式化打印   ensure   int   inf   printer   

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

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!