Python 格式化打印 dict、json 数据

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
}

猜你喜欢

转载自www.cnblogs.com/lowmanisbusy/p/12683897.html