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
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM