2021-04-03に投稿

Python 標準ライブラリ pprint 整形した出力

Pythonの標準にあるpprintを使うとリストや辞書の情報を見やすい形で整形して出力(pretty-print)できます。

ppritの宣言と使用例

import pprint

# PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True)
# indent インデントのサイズ
# width 1行の文字列
# depth 入れ子の深さの上限
# stream 出力先のストリーム
# compact 1行内にできるだけ収めるように出力するか
# sort_dicts キーの順序でソートするか
pp = pprint.PrettyPrinter()
items = { chr(x+64) * 5 : { chr(x + y + 96 + (1 if y %2 == 0 else -1)) + str(x)  : [ z for z in range(y+1)] for y in range(10)} for x in range(1,3) }
pp.pprint(items)
"""
{'AAAAA': {'a1': [0, 1],
           'b1': [0],
           'c1': [0, 1, 2, 3],
           'd1': [0, 1, 2],
           'e1': [0, 1, 2, 3, 4, 5],
           'f1': [0, 1, 2, 3, 4],
           'g1': [0, 1, 2, 3, 4, 5, 6, 7],
           'h1': [0, 1, 2, 3, 4, 5, 6],
           'i1': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
           'j1': [0, 1, 2, 3, 4, 5, 6, 7, 8]},
 'BBBBB': {'b2': [0, 1],
           'c2': [0],
           'd2': [0, 1, 2, 3],
           'e2': [0, 1, 2],
           'f2': [0, 1, 2, 3, 4, 5],
           'g2': [0, 1, 2, 3, 4],
           'h2': [0, 1, 2, 3, 4, 5, 6, 7],
           'i2': [0, 1, 2, 3, 4, 5, 6],
           'j2': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
           'k2': [0, 1, 2, 3, 4, 5, 6, 7, 8]}}
"""

# 出力先をファイルにする
with open('sample.txt', mode='w') as f:
    pp = pprint.PrettyPrinter(stream=f)
    pp.pprint(items)
# 各出力フォーマットの例
items = { chr(x+64) * 5 : { chr(x + y + 96 + (1 if y %2 == 0 else -1)) + str(x)  : [ z for z in range(y+1)] for y in range(10)} for x in range(1,3) }

pp = pprint.PrettyPrinter(depth=1)
pp.pprint(items)
"""
{'AAAAA': {...}, 'BBBBB': {...}}
"""

pp = pprint.PrettyPrinter(width=40, compact=True)
pp.pprint(items)
"""
{'AAAAA': {'a1': [0, 1],
           'b1': [0],
           'c1': [0, 1, 2, 3],
           'd1': [0, 1, 2],
           'e1': [0, 1, 2, 3, 4, 5],
           'f1': [0, 1, 2, 3, 4],
           'g1': [0, 1, 2, 3, 4, 5, 6,
                  7],
           'h1': [0, 1, 2, 3, 4, 5, 6],
           'i1': [0, 1, 2, 3, 4, 5, 6,
                  7, 8, 9],
           'j1': [0, 1, 2, 3, 4, 5, 6,
                  7, 8]},
 'BBBBB': {'b2': [0, 1],
           'c2': [0],
           'd2': [0, 1, 2, 3],
           'e2': [0, 1, 2],
           'f2': [0, 1, 2, 3, 4, 5],
           'g2': [0, 1, 2, 3, 4],
           'h2': [0, 1, 2, 3, 4, 5, 6,
                  7],
           'i2': [0, 1, 2, 3, 4, 5, 6],
           'j2': [0, 1, 2, 3, 4, 5, 6,
                  7, 8, 9],
           'k2': [0, 1, 2, 3, 4, 5, 6,
                  7, 8]}}
"""

pp = pprint.PrettyPrinter(width=160, depth=2, compact=True, sort_dicts=False)
pp.pprint(items)
"""
{'AAAAA': {'b1': [...], 'a1': [...], 'd1': [...], 'c1': [...], 'f1': [...], 'e1': [...], 'h1': [...], 'g1': [...], 'j1': [...], 'i1': [...]},
 'BBBBB': {'c2': [...], 'b2': [...], 'e2': [...], 'd2': [...], 'g2': [...], 'f2': [...], 'i2': [...], 'h2': [...], 'k2': [...], 'j2': [...]}}
"""

pprintメソッド

items = { chr(x+64) * 5 : { chr(x + y + 96 + (1 if y %2 == 0 else -1)) + str(x)  : [ {z:z} for z in range(y+1)] for y in range(10)} for x in range(1,3) }
pp = pprint.PrettyPrinter(depth=1)

# pformat(object) 整形した書式で文字列を取得
format_string = pp.pformat(items)
print(format_string) # => {'AAAAA': {...}, 'BBBBB': {...}}

# pprint(object) 整形した文字列を出力
pp.pprint(items)

# isreadable(object) 書式化できるか
pp.isreadable(items) # => True

recursive_obj = {"A":1}
recursive_obj["B"] = recursive_obj
pp.isreadable(recursive_obj) # => False
pp.pprint(recursive_obj) # => {'A': 1, 'B': {...}}

# isrecursive(object) 再帰的であるか
pp.isrecursive(recursive_obj) # => True
pp.isrecursive(items) # => False

# format(object, context, maxlevels, level) 整形した文字列、書式化できるか、再帰を含むかを取得
# object 整形対象のオブジェクト
# context キーを含むディクショナリ
# maxlevels 再帰呼び出しの制限
# level 現在のレベル
pretty_string, isreadable, isrecursive= pp.format(items, {}, 3, 2)
print(pretty_string) # => {'AAAAA': {...}, 'BBBBB': {...}}
print(isreadable) # => False
print(isrecursive) # => False

pprintで定義されている関数

# pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)
# 整形した文字列の取得
format_string = pprint.pformat(items)
print(format_string)

# pp(object, *args, sort_dicts=False, **kwargs)
# 整形した文字列の出力
pprint.pp(items)

# pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)
# 整形した文字列の出力
pprint.pprint(items)

# pprint.isreadable(object) 書式化できるか(再帰的である場合False)
pprint.isreadable(items) # => True

recursive_obj = {"A":1}
recursive_obj["B"] = recursive_obj
pprint.isreadable(recursive_obj) # => False
pprint.pprint(recursive_obj) # => {'A': 1, 'B': <Recursion on dict with id=2029211018496>}

# pprint.isrecursive(object) 再帰的であるか
pprint.isrecursive(recursive_obj) # => True
pprint.isrecursive(items) # => False

# pprint.saferepr(object) 再帰的なオブジェクトを出力
pprint.saferepr(recursive_obj) # => "{'A': 1, 'B': <Recursion on dict with id=2029214155904>}"

Originally published at marusankakusikaku.jp
ツイッターでシェア
みんなに共有、忘れないようにメモ

maru3kaku4kaku

Pythonこつこつ学習中。よく忘れる。

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント